 
 
// <Template>
//   <SolutionTemplate>EF POCO 1</SolutionTemplate>
//   <Version>20110406.1</Version>
//   <Update>True</Update>
// </Template>
#region using
using System;
using System.Collections.Generic;
using System.Text;
using SFSdotNet.Framework.BR;
using System.Linq.Dynamic;
using System.Collections;
using System.Linq;
using LinqKit;
using SFSdotNet.Framework.Entities;
using SFSdotNet.Framework.Linq;
using System.Linq.Expressions;
using System.Data;
using SFSdotNet.Framework;
using SFSdotNet.Framework.Data.Entity;
using SFSdotNet.Framework.My;
using System.Data.EntityClient;
using System.Data.Objects.DataClasses;
using System.Data.Objects;
using EFPocoAdapter;
using SFS.SampleApp.BusinessObjects;
//using SFS.SampleApp.BusinessObjects.EFPocoAdapter;
//using EFPocoAdapter;
using SFS.SampleApp.BusinessObjects.PocoAdapters;
#endregion
namespace SFS.SampleApp.BR
{
public class SinglentonContext
    {
        private static EFPocoContext context = null;
        public static EFPocoContext Instance {
            get {
               if (context == null)
                    context = new EFPocoContext();
                return context;
            }
        }
        /// <summary>
    /// Re-new the singlenton instance
    /// </summary>
    /// <returns></returns>
        public static EFPocoContext RenewInstance() {
            context = new EFPocoContext();
            return context;
        }
    /// <summary>
    /// Get a new instance
    /// </summary>
        public static EFPocoContext NewInstance {
            get {
                return new EFPocoContext();
            }
        }
    }
	
	
		public partial class AddressesBR{
	 	
           
		 #region Partial methods

           partial void OnUpdating(object sender, BusinessRulesEventArgs<Address> e);

            partial void OnUpdated(object sender, BusinessRulesEventArgs<Address> e);

            partial void OnCreating(object sender, BusinessRulesEventArgs<Address> e);
            partial void OnCreated(object sender, BusinessRulesEventArgs<Address> e);

            partial void OnDeleting(object sender, BusinessRulesEventArgs<Address> e);
            partial void OnDeleted(object sender, BusinessRulesEventArgs<Address> e);

            partial void OnGetting(object sender, BusinessRulesEventArgs<Address> e);
            partial void OnTaken(object sender, BusinessRulesEventArgs<Address> e);
            partial void OnCounting(object sender, BusinessRulesEventArgs<Address> e);
 
 
            #endregion
			
		private static AddressesBR singlenton =null;
				public static AddressesBR NewInstance(){
					return  new AddressesBR();
					
				}
		public static AddressesBR Instance{
			get{
				if (singlenton == null)
					singlenton = new AddressesBR();
				return singlenton;
			}
		}
		private bool preventSecurityRestrictions = false;

		#region Fields
        EFPocoContext context = null;
        #endregion
        #region Constructor
        public AddressesBR()
        {
            context = new EFPocoContext();
        }
		 public AddressesBR(bool preventSecurity)
            {
                this.preventSecurityRestrictions = preventSecurity;
				context = new EFPocoContext();
            }
        #endregion
		
		#region Get

 		public IQueryable<Address> Get()
        {
            //using (EFContext con = new EFContext())
            //{
				EFContext con = new EFContext();
                var query = con.Addresses.AsQueryable();
                con.ContextOptions.ProxyCreationEnabled = false;

                //query = ContextQueryBuilder<Nutrient>.ApplyContextQuery(query, contextRequest);

                return query;




            //}

        }
		
		public List<Address> GetAll()
        {
            return this.GetBy(p => true);
        }
        public List<Address> GetAll(string includes)
        {
            return this.GetBy(p => true, includes);
        }
        public Address GetByKey(Int32 addressID)
        {
            return GetByKey(addressID, true);
        }
        public Address GetByKey(Int32 addressID, bool loadIncludes)
        {
            Address item = null;
			var query = PredicateBuilder.True<Address>();
                    
			string strWhere = "AddressID = " + addressID.ToString();
            Expression<Func<Address, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<Address, bool>(strWhere);
			
			 ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = strWhere;

			//item = GetBy(predicate, loadIncludes, contextRequest).FirstOrDefault();
			item = GetBy(strWhere,loadIncludes,contextRequest).FirstOrDefault();
            return item;
        }
         public List<Address> GetBy(string strWhere, bool loadRelations, ContextRequest contextRequest)
        {
            if (!loadRelations)
                return GetBy(strWhere, contextRequest);
            else
                return GetBy(strWhere, contextRequest, "");

        }
		  public List<Address> GetBy(string strWhere, bool loadRelations)
        {
              if (!loadRelations)
                return GetBy(strWhere, new ContextRequest());
            else
                return GetBy(strWhere, new ContextRequest(), "");

        }
         public Address GetByKey(Int32 addressID, params Expression<Func<Address, object>>[] includes)
        {
            Address item = null;
			string strWhere = "AddressID = " + addressID.ToString();
          Expression<Func<Address, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<Address, bool>(strWhere);
			
        item = GetBy(predicate, includes).FirstOrDefault();
         ////   item = GetBy(strWhere,includes).FirstOrDefault();
			return item;

        }
        public Address GetByKey(Int32 addressID, string includes)
        {
            Address item = null;
			string strWhere = "AddressID = " + addressID.ToString();
            
			
            item = GetBy(strWhere, includes).FirstOrDefault();
            return item;

        }

        #region Dynamic Predicate
        public List<Address> GetBy(Expression<Func<Address, bool>> predicate, int? pageSize, int? page)
        {
            return this.GetBy(predicate, pageSize, page, null, null);
        }
        public List<Address> GetBy(Expression<Func<Address, bool>> predicate, ContextRequest contextRequest)
        {

            return GetBy(predicate, contextRequest,"");
        }
        
        public List<Address> GetBy(Expression<Func<Address, bool>> predicate, ContextRequest contextRequest, params Expression<Func<Address, object>>[] includes)
        {
            StringBuilder sb = new StringBuilder();
           if (includes != null)
            {
                foreach (var path in includes)
                {

						if (sb.Length > 0) sb.Append(",");
						sb.Append(SFSdotNet.Framework.Linq.Utils.IncludeToString<Address>(path));

               }
            }
            return GetBy(predicate, contextRequest, sb.ToString());
        }
        
        
        public List<Address> GetBy(Expression<Func<Address, bool>> predicate, string includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";

            return GetBy(predicate, context, includes);
        }

        public List<Address> GetBy(Expression<Func<Address, bool>> predicate, params Expression<Func<Address, object>>[] includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";
            return GetBy(predicate, context, includes);
        }

      
		public bool DisableCache { get; set; }
		 public List<Address> GetBy(Expression<Func<Address, bool>> predicate, ContextRequest contextRequest, string includes)
        {
            using (EFPocoContext con = new EFPocoContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;

				List<Address> result = null;
                 e = null;
                OnGetting(con,e = new BusinessRulesEventArgs<Address>() { FilterExpression = predicate, ContextRequest = contextRequest, FilterExpressionString = contextRequest.CustomQuery.FilterExpressionString});
				   if (e != null) {
				    predicate = e.FilterExpression;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				con.EnableChangeTrackingUsingProxies = false;
				con.WrappedContext.Addresses.MergeOption = MergeOption.NoTracking;
                con.WrappedContext.ContextOptions.ProxyCreationEnabled = false;
                if (predicate == null) predicate = PredicateBuilder.True<Address>();
                
                var es = con.Addresses;
				 
                IQueryable<Address> query = es.AsQueryable();

                                if (!string.IsNullOrEmpty(includes))
                {
                    foreach (string include in includes.Split(char.Parse(",")))
                    {
						if (!string.IsNullOrEmpty(include))
                            query = query.Include(include);
                    }
                }
				query =query.Where(predicate);
                query = ContextQueryBuilder<Address>.ApplyContextQuery(query, contextRequest);

                result = query.ToList<Address>();
				e = null;
				OnTaken(this, e = new BusinessRulesEventArgs<Address>() { Items= result, FilterExpression = predicate });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
        public List<Address> GetBy(string predicateString, ContextRequest contextRequest, string includes)
        {
            using (EFContext con = new EFContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;


				List<Address> result = null;
                 e = null;
                  OnGetting(con,e = new BusinessRulesEventArgs<Address>() {  ContextRequest = contextRequest, FilterExpressionString = predicateString });
			   	if (e != null) {
				    predicateString = e.FilterExpressionString;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				//con.EnableChangeTrackingUsingProxies = false;
				con.Addresses.MergeOption = MergeOption.NoTracking;
                con.ContextOptions.ProxyCreationEnabled = false;
                //if (predicate == null) predicate = PredicateBuilder.True<Address>();
                
                var es = con.Addresses;
				IQueryable<Address> query = es.AsQueryable();

		
				// include relations FK
				if(string.IsNullOrEmpty(includes) ){
					includes ="";
				}
				
				//string predicateString = predicate.ToDynamicLinq<Address>();
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicateString, ref predicateWithManyRelations, ref predicateWithFKAndComputed);
                var _queryable = query.AsQueryable();
                if (!string.IsNullOrEmpty(predicateWithManyRelations))
                    _queryable = _queryable.Where(predicateWithManyRelations);
 
				var  queryable = _queryable.Select(                    
				p => 
                        new
                    {
					AddressID = p.AddressID
,AddressLine1 = p.AddressLine1
,AddressLine2 = p.AddressLine2
,City = p.City
,StateProvince = p.StateProvince
,CountryRegion = p.CountryRegion
,PostalCode = p.PostalCode
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

,

	
                    }
                    
                    );
					
				
                    if (!string.IsNullOrEmpty(predicateWithFKAndComputed))
                        queryable = queryable.Where(predicateWithFKAndComputed, contextRequest.CustomQuery.ExtraParams);

				QueryComplementOptions queryOps = ContextQueryBuilder.ApplyContextQuery(contextRequest);
            	if (!string.IsNullOrEmpty(queryOps.OrderByAndSort))
					queryable = queryable.OrderBy(queryOps.OrderByAndSort);
               	if (queryOps.Skip != null)
                {
                    queryable = queryable.Skip(queryOps.Skip.Value);
                }
                if (queryOps.PageSize != null)
                {
                    queryable = queryable.Take (queryOps.PageSize.Value);
                }
                result = queryable.AsEnumerable().
                    Select(
                    p =>  new Address()
                    {
					AddressID = p.AddressID
,AddressLine1 = p.AddressLine1
,AddressLine2 = p.AddressLine2
,City = p.City
,StateProvince = p.StateProvince
,CountryRegion = p.CountryRegion
,PostalCode = p.PostalCode
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

                    }
                     ).ToList();

				e = null;
			OnTaken(this, e = new BusinessRulesEventArgs<Address>() { Items= result, FilterExpressionString  = predicateString });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
		public List<Address> GetBy(Expression<Func<Address, bool>> predicate, bool loadRelations, ContextRequest contextRequest)
        {
			if(!loadRelations)
				return GetBy(predicate, contextRequest);
			else
				return GetBy(predicate, contextRequest, "CustomerAddresses,SalesOrderHeaders,SalesOrderHeaders1");

        }

        public List<Address> GetBy(Expression<Func<Address, bool>> predicate, int? pageSize, int? page, string orderBy, SFSdotNet.Framework.Data.SortDirection? sortDirection)
        {
            return GetBy(predicate, new ContextRequest() { CustomQuery = new CustomQuery() { Page = page, PageSize = pageSize, OrderBy = orderBy, SortDirection = sortDirection } });
        }
        public List<Address> GetBy(Expression<Func<Address, bool>> predicate)
        {
		
			ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = null;
            return this.GetBy(predicate, contextRequest, "");
        }
        #endregion
        #region Dynamic String
		private string GetSpecificFilter(string filter) {
            string result = "";
		    string linqFilter = String.Empty;
            string freeTextFilter = String.Empty;
            if (filter.Contains("|"))
            {
                linqFilter = filter.Split(char.Parse("|"))[0];
                freeTextFilter = filter.Split(char.Parse("|"))[1];
            }
 			else {
                linqFilter = filter;
            }
            string specificFilter = linqFilter;
            if (!string.IsNullOrEmpty(freeTextFilter))
            {
                System.Text.StringBuilder sbCont = new System.Text.StringBuilder();
                if (specificFilter.Length > 0)
                {
                    sbCont.Append(" AND ");
                    sbCont.Append(" ({0})");
                }
                else
                {
                    sbCont.Append("{0}");
                }
                var words = freeTextFilter.Split(char.Parse(" "));
                System.Text.StringBuilder sbSpec = new System.Text.StringBuilder();
                 int nWords = 1;
				foreach (var word in words)
                {
                    if (sbSpec.Length > 0) sbSpec.Append(" AND ");
                    sbSpec.Append("(");
					
	
					
											
					sbSpec.Append(string.Format(@"AddressLine1.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"AddressLine2.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"City.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"StateProvince.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"CountryRegion.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"PostalCode.Contains(""{0}"")", word));

					
	
					
	
					
			
                    sbSpec.Append(")");
					
					nWords++;

                }
                specificFilter = string.Format("{0}{1}", specificFilter, string.Format(sbCont.ToString(), sbSpec.ToString()));
            }
			result = specificFilter;
			
			return result;

		}
		public List<Address> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params object[] extraParams)
        {
        	string specificFilter = "";
            if (!string.IsNullOrEmpty(filter))
              specificFilter=  GetSpecificFilter(filter);
            if (string.IsNullOrEmpty(orderBy))
            {
			                orderBy = "AddressLine1";
            }
			SFSdotNet.Framework.Data.SortDirection direction = SFSdotNet.Framework.Data.SortDirection.Ascending;
            if (!string.IsNullOrEmpty(orderDir))
            {
                if (orderDir == "desc")
                    direction = SFSdotNet.Framework.Data.SortDirection.Descending;
            }
            return BR.AddressesBR.Instance.GetBy(specificFilter,
                new SFSdotNet.Framework.My.ContextRequest()
                {
                    CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
                    {
						ExtraParams= extraParams,
               
                        OrderBy = orderBy,
                        SortDirection = direction,
                        Page = page,
                        PageSize = pageSize
                    }
                });
        }


        public List<Address> GetBy(string strWhere, ContextRequest contextRequest)
        {
        	#region old code
				Expression<Func<Address, bool>> predicate = null;
                if (!string.IsNullOrEmpty(strWhere)){

                    object[] extraParams = null;
                    if (contextRequest != null )
                        if (contextRequest.CustomQuery != null )
                            extraParams = contextRequest.CustomQuery.ExtraParams;
                    predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<Address, bool>(strWhere, extraParams);				}
				 if (contextRequest == null)
                {
                    contextRequest = new ContextRequest();
                    if (contextRequest.CustomQuery == null)
                        contextRequest.CustomQuery = new CustomQuery();
                }
                
            contextRequest.CustomQuery.FilterExpressionString = strWhere;
				//return GetBy(predicate, contextRequest);  

			#endregion				
				
                    return GetBy(strWhere, contextRequest, "");  


        }
       public List<Address> GetBy(string strWhere)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
			
            return GetBy(strWhere, context, null);
        }

        public List<Address> GetBy(string strWhere, string includes)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
            return GetBy(strWhere, context, includes);
        }

        #endregion
        #endregion
		
		  #region SaveOrUpdate
        private Address Save(Address entity, bool saveChanges, EFPocoContext con)
        {
				ObjectContext context = null;
            return Update(entity, saveChanges, out context);

			
        }

 		 public Address Create(Address entity)
        {
				ObjectContext context = null;
				return this.Create(entity, true, out context);

        }
         public Address Create(Address entity, bool saveChanges, out ObjectContext context)
        {
                    return Create(entity, saveChanges , out context, null);
        }
         public Address Create(Address entity, params Expression<Func<Address,object>>[] paths)
        {
            ObjectContext context = null;
            if(paths != null)
				return Create(entity, true, out context, paths);
			else 
				return Create(entity, true, out context);
        }
        public Address Create(Address entity, bool saveChanges, out ObjectContext context, params Expression<Func<Address,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				Address itemResult = null;
#region Autos
	

			entity.rowguid = Guid.NewGuid();
	
	

#endregion
                e = null;
                OnCreating(this,e = new BusinessRulesEventArgs<Address>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							context = null;
							return e.Item;

						}
					}



				AddressAdapter adapter = con.GetAdapterObject<AddressAdapter>(entity);;
				List<Expression<Func<AddressAdapter, object>>> paths = new List<Expression<Func<AddressAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(AddressAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<AddressAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "CustomerAddresses":
								path = p => p.CustomerAddresses.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.CustomerAddresses.First().Customer.WithoutUpdate();											
							break;
                        
							case "SalesOrderHeaders":
								path = p => p.SalesOrderHeaders.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.SalesOrderHeaders.First().Customer.WithoutUpdate();											
							break;
                        
							case "SalesOrderHeaders1":
								path = p => p.SalesOrderHeaders1.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.SalesOrderHeaders1.First().Customer.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        
                       paths.Add(path.Expand());
                    }
                }
                object aux = null;
					//paths = pathBuilder.ToArray();

#region Childs CustomerAddresses 
				if (adapter.CustomerAddresses != null)
                {
                    foreach (var item in adapter.CustomerAddresses)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("CustomerAddresses", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.CustomerAddresses.First().WithoutUpdate());
								
							if (item.Address == null)
								item.Address = adapter;

						if (item.Customer != null){
							item.Customer.EntityKey = con.WrappedContext.CreateEntityKey("Customers", item.Customer);
                            
             
						}								
								item.EntityKey = null;
							}

                    }
					if (adapter.CustomerAddresses.Count > 0){
						paths.Add(p => p.CustomerAddresses.First().WithoutUpdate());
						paths.Add(p => p.CustomerAddresses.First().Customer.WithoutUpdate());
					
					}
                }
#endregion 

#region Childs SalesOrderHeaders 
				if (adapter.SalesOrderHeaders != null)
                {
                    foreach (var item in adapter.SalesOrderHeaders)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderHeaders", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.SalesOrderHeaders.First().WithoutUpdate());
								
							if (item.Address == null)
								item.Address = adapter;

						if (item.Address1 != null){
							item.Address1.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", item.Address1);
                            
             
						}								
						if (item.Customer != null){
							item.Customer.EntityKey = con.WrappedContext.CreateEntityKey("Customers", item.Customer);
                            
             
						}								
								item.EntityKey = null;
							}

                    }
					if (adapter.SalesOrderHeaders.Count > 0){
						paths.Add(p => p.SalesOrderHeaders.First().WithoutUpdate());
						paths.Add(p => p.SalesOrderHeaders.First().Address1.WithoutUpdate());
paths.Add(p => p.SalesOrderHeaders.First().Customer.WithoutUpdate());
					
					}
                }
#endregion 

#region Childs SalesOrderHeaders1 
				if (adapter.SalesOrderHeaders1 != null)
                {
                    foreach (var item in adapter.SalesOrderHeaders1)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderHeaders", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.SalesOrderHeaders1.First().WithoutUpdate());
								
						if (item.Address != null){
							item.Address.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", item.Address);
                            
             
						}								
							if (item.Address1 == null)
								item.Address1 = adapter;

						if (item.Customer != null){
							item.Customer.EntityKey = con.WrappedContext.CreateEntityKey("Customers", item.Customer);
                            
             
						}								
								item.EntityKey = null;
							}

                    }
					if (adapter.SalesOrderHeaders1.Count > 0){
						paths.Add(p => p.SalesOrderHeaders1.First().WithoutUpdate());
						paths.Add(p => p.SalesOrderHeaders1.First().Address.WithoutUpdate());
paths.Add(p => p.SalesOrderHeaders1.First().Customer.WithoutUpdate());
					
					}
                }
#endregion 




                //con.WrappedContext.AttachObjectGraph<AddressAdapter>(adapter, p=>p.CustomerAddresses, p=>p.SalesOrderHeaders, p=>p.SalesOrderHeaders1);
                con.WrappedContext.AttachObjectGraph<AddressAdapter>(adapter, paths.ToArray());
              	if (saveChanges){
                    con.WrappedContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
					 
				}
                else
                    con.WrappedContext.SaveChanges(SaveOptions.None);
                if (!saveChanges)
                    context = con.WrappedContext;
                else
                    context = null;
				itemResult = adapter.PocoEntity;
                OnCreated(this, e = new BusinessRulesEventArgs<Address>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });
                return itemResult;
            }
        }
        BusinessRulesEventArgs<Address> e = null;
        public void Create(List<Address> entities)
        {
				ObjectContext context = null;
				foreach (Address entity in entities)
				{
					this.Create(entity, true, out context);
				}

				
				
        }

        public Address Update(Address entity)
        {
			ObjectContext context = null;
            return Update(entity, true, out context, null);

        }
         public Address Update(Address entity, params Expression<Func<Address, object>>[] paths)
        {
			  ObjectContext context = null;
            return Update(entity, true, out context, paths);
         }
        public Address Update(Address entity, bool saveChanges, out ObjectContext outcontext)
        {
			return Update(entity, saveChanges, out outcontext, null);
		}
         public Address Update(Address entity, bool saveChanges, out ObjectContext outcontext, params Expression<Func<Address,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				Address  itemResult = null;

	

				e = null;
                OnUpdating(this,e = new BusinessRulesEventArgs<Address>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							outcontext = null;
							return e.Item;

						}
					}

                AddressAdapter adapter = con.GetAdapterObject<AddressAdapter>(entity);
                adapter.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", adapter);
				    var es = con.Addresses;
				List<Expression<Func<AddressAdapter, object>>> paths = new List<Expression<Func<AddressAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(AddressAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<AddressAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "CustomerAddresses":
								//path = p => member;
								path = p => p.CustomerAddresses.First().WithoutUpdate();
				//				path = p => p.CustomerAddresses.First().Customer.WithoutUpdate();											
							break;
                        
							case "SalesOrderHeaders":
								//path = p => member;
								path = p => p.SalesOrderHeaders.First().WithoutUpdate();
				//				path = p => p.SalesOrderHeaders.First().Customer.WithoutUpdate();											
							break;
                        
							case "SalesOrderHeaders1":
								//path = p => member;
								path = p => p.SalesOrderHeaders1.First().WithoutUpdate();
				//				path = p => p.SalesOrderHeaders1.First().Customer.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        paths.Add(path.Expand());
 					}
                }
                else {
                  paths = new List<Expression<Func<AddressAdapter, object>>>();

					//List<Expression<Func<AddressAdapter,object>>> pathBuilder = new List<Expression<Func<AddressAdapter,object>>>();
		
					//paths = pathBuilder.ToArray();		
			}
			object aux = null;
				if (adapter.CustomerAddresses != null)
                {
                    foreach (var item in adapter.CustomerAddresses)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("CustomerAddresses", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }
				if (adapter.SalesOrderHeaders != null)
                {
                    foreach (var item in adapter.SalesOrderHeaders)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderHeaders", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }
				if (adapter.SalesOrderHeaders1 != null)
                {
                    foreach (var item in adapter.SalesOrderHeaders1)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderHeaders", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }



                //con.AttachObjectGraph<Address>(adapter, p=>p.CustomerAddresses, p=>p.SalesOrderHeaders, p=>p.SalesOrderHeaders1);
                con.WrappedContext.AttachObjectGraph<AddressAdapter>(adapter, paths.ToArray());
				if (saveChanges){
                	con.WrappedContext.SaveChanges();
					 
					}
                if(!saveChanges)
					outcontext = con.WrappedContext;
				else
					outcontext = null;
				itemResult = adapter.PocoEntity;
				OnUpdated(this, e = new BusinessRulesEventArgs<Address>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });

              	return itemResult;

			  }
        }
        public Address Save(Address entity)
        {
			return Save(entity, true, null);
        }
        public int Save(List<Address> entities)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
			
            int n = 0;
            foreach (Address item in entities)
            {
                try
                {
                    this.Save(item, false, con);
                    n++;
                }catch (Exception ex){
                    SFSdotNet.Framework.My.EventLog.Exception(ex);
                }
            }
            con.SaveChanges();
            return n;
            }
        }
        #endregion
        #region Delete
        public void Delete(Address entity)
        {
				ObjectContext context = null;
				this.Delete(entity, true, out context);
			
        }

        
        public void Delete(Address entity, bool saveChanges, out  ObjectContext context)
        {
			using (EFPocoContext _con = new EFPocoContext())
			{
				int result = 0;
				
               	BusinessRulesEventArgs<Address> _e = null;
                OnDeleting(this,_e = new BusinessRulesEventArgs<Address>() { Item=entity, SaveChanges =saveChanges });
				   if (_e != null) {
						if (_e.Cancel)
						{
							context = null;
							return;

						}
					}


				AddressAdapter adapter = _con.GetAdapterObject<AddressAdapter>(entity);
                adapter.EntityKey = _con.WrappedContext.CreateEntityKey("Addresses", adapter);
                
	            //adapter = _con.WrappedContext.AttachObjectGraph<AddressAdapter>(adapter);
				_con.WrappedContext.AttachTo("Addresses", adapter);
                
									_con.WrappedContext.DeleteObject(adapter);
                				
				if (!saveChanges)
                    context = _con.WrappedContext;
                else
                    context = null;
				 SaveOptions saveOption = SaveOptions.None;
                if (saveChanges)
                    saveOption = SaveOptions.AcceptAllChangesAfterSave;

				result = _con.WrappedContext.SaveChanges(saveOption);
				if (saveChanges){
					
					}
				if (_e == null)
					_e = new BusinessRulesEventArgs<Address>() { Item = entity };
                OnDeleted(this, _e );

				//return null;
			}            
        }
        public void Delete(List<Address> entities)
        {
				ObjectContext context = null;
			
				foreach (Address item in entities)
				{
					this.Delete(item, true, out context);
				}
			

			
        }
        #endregion
 
        #region GetCount
        public int GetCount(Expression<Func<Address, bool>> predicate)
        {
		
			using (EFPocoContext con = new EFPocoContext())
			{


				if (predicate == null) predicate = PredicateBuilder.True<Address>();
				
				return con.Addresses.Count(predicate);
			}

        }
        public int GetCount(string predicate)
        {
			e = null;
            OnCounting(this, e = new BusinessRulesEventArgs<Address>() {  FilterExpressionString = predicate });
            if (e != null)
            {
                if (e.Cancel)
                {
                    context = null;
                    return e.CountResult;

                }
                predicate = e.FilterExpressionString;
            
            }
					predicate = GetSpecificFilter(predicate);
			using (EFContext con = new EFContext())
			{
				   
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicate, ref predicateWithManyRelations, ref predicateWithFKAndComputed);

                if (!string.IsNullOrEmpty(predicate))
                {
				
					
                    return con.Addresses.Count(System.Linq.Dynamic.DynamicExpression.ParseLambda<Address, bool>(predicate));
					
                }else
                    return con.Addresses.Count();

			}

		}
         public int GetCount()
        {
            return GetCount(p => true);
        }
        #endregion
        
         public Address Update(Address entity, string paths)
        {
            return Update(entity, paths.Split(char.Parse(",")));
            
        }

        public Address Update(Address entity, string[] paths)
        {
            // Translate
            List<Expression<Func<Address, object>>> pathList = new List<Expression<Func<Address, object>>>();
            for (int i = 0; i <= paths.Length -1; i++)
            {
                var param = Expression.Parameter(typeof(Address), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<Address, object>> path = p => member;
                pathList.Add(path.Expand());
            }
           return Update(entity, pathList.ToArray());
        }

        public void Update(List<Address> entities, string paths)
        {
            foreach (var entity in entities )
            {
                Update(entity, paths);
            }
        }

        public Address Create(Address entity, string paths)
        {
			if(string.IsNullOrEmpty(paths))
				return Create(entity);
				
            return Create(entity, paths.Split(char.Parse(",")));
        }

        public  void Create(List<Address> entities, string paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }

        public void Create(List<Address> entities, string[] paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }
        
        public Address  Create(Address entity, string[] paths)
        {
            List<Expression<Func<Address, object>>> pathList = new List<Expression<Func<Address, object>>>();
            for (int i = 0; i < paths.Length - 1; i++)
            {
                var param = Expression.Parameter(typeof(Address), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<Address, object>> path = p => member;
                pathList.Add(path.Expand());
            }
            return Create(entity, pathList.ToArray());
        }
        public void Delete(List<Address.CompositeKey> entityKeys)
        {

            List<Address> items = new List<Address>();
            foreach (var itemKey in entityKeys)
            {
                items.Add(GetByKey(itemKey.AddressID));
            }

            Delete(items);

        }
		
		
	}
		public partial class CustomersBR{
	 	
           
		 #region Partial methods

           partial void OnUpdating(object sender, BusinessRulesEventArgs<Customer> e);

            partial void OnUpdated(object sender, BusinessRulesEventArgs<Customer> e);

            partial void OnCreating(object sender, BusinessRulesEventArgs<Customer> e);
            partial void OnCreated(object sender, BusinessRulesEventArgs<Customer> e);

            partial void OnDeleting(object sender, BusinessRulesEventArgs<Customer> e);
            partial void OnDeleted(object sender, BusinessRulesEventArgs<Customer> e);

            partial void OnGetting(object sender, BusinessRulesEventArgs<Customer> e);
            partial void OnTaken(object sender, BusinessRulesEventArgs<Customer> e);
            partial void OnCounting(object sender, BusinessRulesEventArgs<Customer> e);
 
 
            #endregion
			
		private static CustomersBR singlenton =null;
				public static CustomersBR NewInstance(){
					return  new CustomersBR();
					
				}
		public static CustomersBR Instance{
			get{
				if (singlenton == null)
					singlenton = new CustomersBR();
				return singlenton;
			}
		}
		private bool preventSecurityRestrictions = false;

		#region Fields
        EFPocoContext context = null;
        #endregion
        #region Constructor
        public CustomersBR()
        {
            context = new EFPocoContext();
        }
		 public CustomersBR(bool preventSecurity)
            {
                this.preventSecurityRestrictions = preventSecurity;
				context = new EFPocoContext();
            }
        #endregion
		
		#region Get

 		public IQueryable<Customer> Get()
        {
            //using (EFContext con = new EFContext())
            //{
				EFContext con = new EFContext();
                var query = con.Customers.AsQueryable();
                con.ContextOptions.ProxyCreationEnabled = false;

                //query = ContextQueryBuilder<Nutrient>.ApplyContextQuery(query, contextRequest);

                return query;




            //}

        }
		
		public List<Customer> GetAll()
        {
            return this.GetBy(p => true);
        }
        public List<Customer> GetAll(string includes)
        {
            return this.GetBy(p => true, includes);
        }
        public Customer GetByKey(Int32 customerID)
        {
            return GetByKey(customerID, true);
        }
        public Customer GetByKey(Int32 customerID, bool loadIncludes)
        {
            Customer item = null;
			var query = PredicateBuilder.True<Customer>();
                    
			string strWhere = "CustomerID = " + customerID.ToString();
            Expression<Func<Customer, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<Customer, bool>(strWhere);
			
			 ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = strWhere;

			//item = GetBy(predicate, loadIncludes, contextRequest).FirstOrDefault();
			item = GetBy(strWhere,loadIncludes,contextRequest).FirstOrDefault();
            return item;
        }
         public List<Customer> GetBy(string strWhere, bool loadRelations, ContextRequest contextRequest)
        {
            if (!loadRelations)
                return GetBy(strWhere, contextRequest);
            else
                return GetBy(strWhere, contextRequest, "");

        }
		  public List<Customer> GetBy(string strWhere, bool loadRelations)
        {
              if (!loadRelations)
                return GetBy(strWhere, new ContextRequest());
            else
                return GetBy(strWhere, new ContextRequest(), "");

        }
         public Customer GetByKey(Int32 customerID, params Expression<Func<Customer, object>>[] includes)
        {
            Customer item = null;
			string strWhere = "CustomerID = " + customerID.ToString();
          Expression<Func<Customer, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<Customer, bool>(strWhere);
			
        item = GetBy(predicate, includes).FirstOrDefault();
         ////   item = GetBy(strWhere,includes).FirstOrDefault();
			return item;

        }
        public Customer GetByKey(Int32 customerID, string includes)
        {
            Customer item = null;
			string strWhere = "CustomerID = " + customerID.ToString();
            
			
            item = GetBy(strWhere, includes).FirstOrDefault();
            return item;

        }

        #region Dynamic Predicate
        public List<Customer> GetBy(Expression<Func<Customer, bool>> predicate, int? pageSize, int? page)
        {
            return this.GetBy(predicate, pageSize, page, null, null);
        }
        public List<Customer> GetBy(Expression<Func<Customer, bool>> predicate, ContextRequest contextRequest)
        {

            return GetBy(predicate, contextRequest,"");
        }
        
        public List<Customer> GetBy(Expression<Func<Customer, bool>> predicate, ContextRequest contextRequest, params Expression<Func<Customer, object>>[] includes)
        {
            StringBuilder sb = new StringBuilder();
           if (includes != null)
            {
                foreach (var path in includes)
                {

						if (sb.Length > 0) sb.Append(",");
						sb.Append(SFSdotNet.Framework.Linq.Utils.IncludeToString<Customer>(path));

               }
            }
            return GetBy(predicate, contextRequest, sb.ToString());
        }
        
        
        public List<Customer> GetBy(Expression<Func<Customer, bool>> predicate, string includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";

            return GetBy(predicate, context, includes);
        }

        public List<Customer> GetBy(Expression<Func<Customer, bool>> predicate, params Expression<Func<Customer, object>>[] includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";
            return GetBy(predicate, context, includes);
        }

      
		public bool DisableCache { get; set; }
		 public List<Customer> GetBy(Expression<Func<Customer, bool>> predicate, ContextRequest contextRequest, string includes)
        {
            using (EFPocoContext con = new EFPocoContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;

				List<Customer> result = null;
                 e = null;
                OnGetting(con,e = new BusinessRulesEventArgs<Customer>() { FilterExpression = predicate, ContextRequest = contextRequest, FilterExpressionString = contextRequest.CustomQuery.FilterExpressionString});
				   if (e != null) {
				    predicate = e.FilterExpression;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				con.EnableChangeTrackingUsingProxies = false;
				con.WrappedContext.Customers.MergeOption = MergeOption.NoTracking;
                con.WrappedContext.ContextOptions.ProxyCreationEnabled = false;
                if (predicate == null) predicate = PredicateBuilder.True<Customer>();
                
                var es = con.Customers;
				 
                IQueryable<Customer> query = es.AsQueryable();

                                if (!string.IsNullOrEmpty(includes))
                {
                    foreach (string include in includes.Split(char.Parse(",")))
                    {
						if (!string.IsNullOrEmpty(include))
                            query = query.Include(include);
                    }
                }
				query =query.Where(predicate);
                query = ContextQueryBuilder<Customer>.ApplyContextQuery(query, contextRequest);

                result = query.ToList<Customer>();
				e = null;
				OnTaken(this, e = new BusinessRulesEventArgs<Customer>() { Items= result, FilterExpression = predicate });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
        public List<Customer> GetBy(string predicateString, ContextRequest contextRequest, string includes)
        {
            using (EFContext con = new EFContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;


				List<Customer> result = null;
                 e = null;
                  OnGetting(con,e = new BusinessRulesEventArgs<Customer>() {  ContextRequest = contextRequest, FilterExpressionString = predicateString });
			   	if (e != null) {
				    predicateString = e.FilterExpressionString;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				//con.EnableChangeTrackingUsingProxies = false;
				con.Customers.MergeOption = MergeOption.NoTracking;
                con.ContextOptions.ProxyCreationEnabled = false;
                //if (predicate == null) predicate = PredicateBuilder.True<Customer>();
                
                var es = con.Customers;
				IQueryable<Customer> query = es.AsQueryable();

		
				// include relations FK
				if(string.IsNullOrEmpty(includes) ){
					includes ="";
				}
				
				//string predicateString = predicate.ToDynamicLinq<Customer>();
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicateString, ref predicateWithManyRelations, ref predicateWithFKAndComputed);
                var _queryable = query.AsQueryable();
                if (!string.IsNullOrEmpty(predicateWithManyRelations))
                    _queryable = _queryable.Where(predicateWithManyRelations);
 
				var  queryable = _queryable.Select(                    
				p => 
                        new
                    {
					CustomerID = p.CustomerID
,NameStyle = p.NameStyle
,Title = p.Title
,FirstName = p.FirstName
,MiddleName = p.MiddleName
,LastName = p.LastName
,Suffix = p.Suffix
,CompanyName = p.CompanyName
,SalesPerson = p.SalesPerson
,EmailAddress = p.EmailAddress
,Phone = p.Phone
,PasswordHash = p.PasswordHash
,PasswordSalt = p.PasswordSalt
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

,

	
                    }
                    
                    );
					
				
                    if (!string.IsNullOrEmpty(predicateWithFKAndComputed))
                        queryable = queryable.Where(predicateWithFKAndComputed, contextRequest.CustomQuery.ExtraParams);

				QueryComplementOptions queryOps = ContextQueryBuilder.ApplyContextQuery(contextRequest);
            	if (!string.IsNullOrEmpty(queryOps.OrderByAndSort))
					queryable = queryable.OrderBy(queryOps.OrderByAndSort);
               	if (queryOps.Skip != null)
                {
                    queryable = queryable.Skip(queryOps.Skip.Value);
                }
                if (queryOps.PageSize != null)
                {
                    queryable = queryable.Take (queryOps.PageSize.Value);
                }
                result = queryable.AsEnumerable().
                    Select(
                    p =>  new Customer()
                    {
					CustomerID = p.CustomerID
,NameStyle = p.NameStyle
,Title = p.Title
,FirstName = p.FirstName
,MiddleName = p.MiddleName
,LastName = p.LastName
,Suffix = p.Suffix
,CompanyName = p.CompanyName
,SalesPerson = p.SalesPerson
,EmailAddress = p.EmailAddress
,Phone = p.Phone
,PasswordHash = p.PasswordHash
,PasswordSalt = p.PasswordSalt
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

                    }
                     ).ToList();

				e = null;
			OnTaken(this, e = new BusinessRulesEventArgs<Customer>() { Items= result, FilterExpressionString  = predicateString });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
		public List<Customer> GetBy(Expression<Func<Customer, bool>> predicate, bool loadRelations, ContextRequest contextRequest)
        {
			if(!loadRelations)
				return GetBy(predicate, contextRequest);
			else
				return GetBy(predicate, contextRequest, "CustomerAddresses,SalesOrderHeaders");

        }

        public List<Customer> GetBy(Expression<Func<Customer, bool>> predicate, int? pageSize, int? page, string orderBy, SFSdotNet.Framework.Data.SortDirection? sortDirection)
        {
            return GetBy(predicate, new ContextRequest() { CustomQuery = new CustomQuery() { Page = page, PageSize = pageSize, OrderBy = orderBy, SortDirection = sortDirection } });
        }
        public List<Customer> GetBy(Expression<Func<Customer, bool>> predicate)
        {
		
			ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = null;
            return this.GetBy(predicate, contextRequest, "");
        }
        #endregion
        #region Dynamic String
		private string GetSpecificFilter(string filter) {
            string result = "";
		    string linqFilter = String.Empty;
            string freeTextFilter = String.Empty;
            if (filter.Contains("|"))
            {
                linqFilter = filter.Split(char.Parse("|"))[0];
                freeTextFilter = filter.Split(char.Parse("|"))[1];
            }
 			else {
                linqFilter = filter;
            }
            string specificFilter = linqFilter;
            if (!string.IsNullOrEmpty(freeTextFilter))
            {
                System.Text.StringBuilder sbCont = new System.Text.StringBuilder();
                if (specificFilter.Length > 0)
                {
                    sbCont.Append(" AND ");
                    sbCont.Append(" ({0})");
                }
                else
                {
                    sbCont.Append("{0}");
                }
                var words = freeTextFilter.Split(char.Parse(" "));
                System.Text.StringBuilder sbSpec = new System.Text.StringBuilder();
                 int nWords = 1;
				foreach (var word in words)
                {
                    if (sbSpec.Length > 0) sbSpec.Append(" AND ");
                    sbSpec.Append("(");
					
	
					
	
					
											
					sbSpec.Append(string.Format(@"Title.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"FirstName.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"MiddleName.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"LastName.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"Suffix.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"CompanyName.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"SalesPerson.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"EmailAddress.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"Phone.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"PasswordHash.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"PasswordSalt.Contains(""{0}"")", word));

					
	
					
	
					
			
                    sbSpec.Append(")");
					
					nWords++;

                }
                specificFilter = string.Format("{0}{1}", specificFilter, string.Format(sbCont.ToString(), sbSpec.ToString()));
            }
			result = specificFilter;
			
			return result;

		}
		public List<Customer> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params object[] extraParams)
        {
        	string specificFilter = "";
            if (!string.IsNullOrEmpty(filter))
              specificFilter=  GetSpecificFilter(filter);
            if (string.IsNullOrEmpty(orderBy))
            {
			                orderBy = "Title";
            }
			SFSdotNet.Framework.Data.SortDirection direction = SFSdotNet.Framework.Data.SortDirection.Ascending;
            if (!string.IsNullOrEmpty(orderDir))
            {
                if (orderDir == "desc")
                    direction = SFSdotNet.Framework.Data.SortDirection.Descending;
            }
            return BR.CustomersBR.Instance.GetBy(specificFilter,
                new SFSdotNet.Framework.My.ContextRequest()
                {
                    CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
                    {
						ExtraParams= extraParams,
               
                        OrderBy = orderBy,
                        SortDirection = direction,
                        Page = page,
                        PageSize = pageSize
                    }
                });
        }


        public List<Customer> GetBy(string strWhere, ContextRequest contextRequest)
        {
        	#region old code
				Expression<Func<Customer, bool>> predicate = null;
                if (!string.IsNullOrEmpty(strWhere)){

                    object[] extraParams = null;
                    if (contextRequest != null )
                        if (contextRequest.CustomQuery != null )
                            extraParams = contextRequest.CustomQuery.ExtraParams;
                    predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<Customer, bool>(strWhere, extraParams);				}
				 if (contextRequest == null)
                {
                    contextRequest = new ContextRequest();
                    if (contextRequest.CustomQuery == null)
                        contextRequest.CustomQuery = new CustomQuery();
                }
                
            contextRequest.CustomQuery.FilterExpressionString = strWhere;
				//return GetBy(predicate, contextRequest);  

			#endregion				
				
                    return GetBy(strWhere, contextRequest, "");  


        }
       public List<Customer> GetBy(string strWhere)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
			
            return GetBy(strWhere, context, null);
        }

        public List<Customer> GetBy(string strWhere, string includes)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
            return GetBy(strWhere, context, includes);
        }

        #endregion
        #endregion
		
		  #region SaveOrUpdate
        private Customer Save(Customer entity, bool saveChanges, EFPocoContext con)
        {
				ObjectContext context = null;
            return Update(entity, saveChanges, out context);

			
        }

 		 public Customer Create(Customer entity)
        {
				ObjectContext context = null;
				return this.Create(entity, true, out context);

        }
         public Customer Create(Customer entity, bool saveChanges, out ObjectContext context)
        {
                    return Create(entity, saveChanges , out context, null);
        }
         public Customer Create(Customer entity, params Expression<Func<Customer,object>>[] paths)
        {
            ObjectContext context = null;
            if(paths != null)
				return Create(entity, true, out context, paths);
			else 
				return Create(entity, true, out context);
        }
        public Customer Create(Customer entity, bool saveChanges, out ObjectContext context, params Expression<Func<Customer,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				Customer itemResult = null;
#region Autos
	

			entity.rowguid = Guid.NewGuid();
	
	

#endregion
                e = null;
                OnCreating(this,e = new BusinessRulesEventArgs<Customer>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							context = null;
							return e.Item;

						}
					}



				CustomerAdapter adapter = con.GetAdapterObject<CustomerAdapter>(entity);;
				List<Expression<Func<CustomerAdapter, object>>> paths = new List<Expression<Func<CustomerAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(CustomerAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<CustomerAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "CustomerAddresses":
								path = p => p.CustomerAddresses.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.CustomerAddresses.First().Address.WithoutUpdate();											
							break;
                        
							case "SalesOrderHeaders":
								path = p => p.SalesOrderHeaders.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.SalesOrderHeaders.First().Address.WithoutUpdate();											
								//path = p => p.SalesOrderHeaders.First().Address1.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        
                       paths.Add(path.Expand());
                    }
                }
                object aux = null;
					//paths = pathBuilder.ToArray();

#region Childs CustomerAddresses 
				if (adapter.CustomerAddresses != null)
                {
                    foreach (var item in adapter.CustomerAddresses)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("CustomerAddresses", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.CustomerAddresses.First().WithoutUpdate());
								
						if (item.Address != null){
							item.Address.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", item.Address);
                            
             
						}								
							if (item.Customer == null)
								item.Customer = adapter;

								item.EntityKey = null;
							}

                    }
					if (adapter.CustomerAddresses.Count > 0){
						paths.Add(p => p.CustomerAddresses.First().WithoutUpdate());
						paths.Add(p => p.CustomerAddresses.First().Address.WithoutUpdate());
					
					}
                }
#endregion 

#region Childs SalesOrderHeaders 
				if (adapter.SalesOrderHeaders != null)
                {
                    foreach (var item in adapter.SalesOrderHeaders)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderHeaders", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.SalesOrderHeaders.First().WithoutUpdate());
								
						if (item.Address != null){
							item.Address.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", item.Address);
                            
             
						}								
						if (item.Address1 != null){
							item.Address1.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", item.Address1);
                            
             
						}								
							if (item.Customer == null)
								item.Customer = adapter;

								item.EntityKey = null;
							}

                    }
					if (adapter.SalesOrderHeaders.Count > 0){
						paths.Add(p => p.SalesOrderHeaders.First().WithoutUpdate());
						paths.Add(p => p.SalesOrderHeaders.First().Address.WithoutUpdate());
paths.Add(p => p.SalesOrderHeaders.First().Address1.WithoutUpdate());
					
					}
                }
#endregion 




                //con.WrappedContext.AttachObjectGraph<CustomerAdapter>(adapter, p=>p.CustomerAddresses, p=>p.SalesOrderHeaders);
                con.WrappedContext.AttachObjectGraph<CustomerAdapter>(adapter, paths.ToArray());
              	if (saveChanges){
                    con.WrappedContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
					 
				}
                else
                    con.WrappedContext.SaveChanges(SaveOptions.None);
                if (!saveChanges)
                    context = con.WrappedContext;
                else
                    context = null;
				itemResult = adapter.PocoEntity;
                OnCreated(this, e = new BusinessRulesEventArgs<Customer>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });
                return itemResult;
            }
        }
        BusinessRulesEventArgs<Customer> e = null;
        public void Create(List<Customer> entities)
        {
				ObjectContext context = null;
				foreach (Customer entity in entities)
				{
					this.Create(entity, true, out context);
				}

				
				
        }

        public Customer Update(Customer entity)
        {
			ObjectContext context = null;
            return Update(entity, true, out context, null);

        }
         public Customer Update(Customer entity, params Expression<Func<Customer, object>>[] paths)
        {
			  ObjectContext context = null;
            return Update(entity, true, out context, paths);
         }
        public Customer Update(Customer entity, bool saveChanges, out ObjectContext outcontext)
        {
			return Update(entity, saveChanges, out outcontext, null);
		}
         public Customer Update(Customer entity, bool saveChanges, out ObjectContext outcontext, params Expression<Func<Customer,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				Customer  itemResult = null;

	

				e = null;
                OnUpdating(this,e = new BusinessRulesEventArgs<Customer>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							outcontext = null;
							return e.Item;

						}
					}

                CustomerAdapter adapter = con.GetAdapterObject<CustomerAdapter>(entity);
                adapter.EntityKey = con.WrappedContext.CreateEntityKey("Customers", adapter);
				    var es = con.Customers;
				List<Expression<Func<CustomerAdapter, object>>> paths = new List<Expression<Func<CustomerAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(CustomerAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<CustomerAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "CustomerAddresses":
								//path = p => member;
								path = p => p.CustomerAddresses.First().WithoutUpdate();
				//				path = p => p.CustomerAddresses.First().Address.WithoutUpdate();											
							break;
                        
							case "SalesOrderHeaders":
								//path = p => member;
								path = p => p.SalesOrderHeaders.First().WithoutUpdate();
				//				path = p => p.SalesOrderHeaders.First().Address.WithoutUpdate();											
				//				path = p => p.SalesOrderHeaders.First().Address1.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        paths.Add(path.Expand());
 					}
                }
                else {
                  paths = new List<Expression<Func<CustomerAdapter, object>>>();

					//List<Expression<Func<CustomerAdapter,object>>> pathBuilder = new List<Expression<Func<CustomerAdapter,object>>>();
		
					//paths = pathBuilder.ToArray();		
			}
			object aux = null;
				if (adapter.CustomerAddresses != null)
                {
                    foreach (var item in adapter.CustomerAddresses)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("CustomerAddresses", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }
				if (adapter.SalesOrderHeaders != null)
                {
                    foreach (var item in adapter.SalesOrderHeaders)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderHeaders", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }



                //con.AttachObjectGraph<Customer>(adapter, p=>p.CustomerAddresses, p=>p.SalesOrderHeaders);
                con.WrappedContext.AttachObjectGraph<CustomerAdapter>(adapter, paths.ToArray());
				if (saveChanges){
                	con.WrappedContext.SaveChanges();
					 
					}
                if(!saveChanges)
					outcontext = con.WrappedContext;
				else
					outcontext = null;
				itemResult = adapter.PocoEntity;
				OnUpdated(this, e = new BusinessRulesEventArgs<Customer>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });

              	return itemResult;

			  }
        }
        public Customer Save(Customer entity)
        {
			return Save(entity, true, null);
        }
        public int Save(List<Customer> entities)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
			
            int n = 0;
            foreach (Customer item in entities)
            {
                try
                {
                    this.Save(item, false, con);
                    n++;
                }catch (Exception ex){
                    SFSdotNet.Framework.My.EventLog.Exception(ex);
                }
            }
            con.SaveChanges();
            return n;
            }
        }
        #endregion
        #region Delete
        public void Delete(Customer entity)
        {
				ObjectContext context = null;
				this.Delete(entity, true, out context);
			
        }

        
        public void Delete(Customer entity, bool saveChanges, out  ObjectContext context)
        {
			using (EFPocoContext _con = new EFPocoContext())
			{
				int result = 0;
				
               	BusinessRulesEventArgs<Customer> _e = null;
                OnDeleting(this,_e = new BusinessRulesEventArgs<Customer>() { Item=entity, SaveChanges =saveChanges });
				   if (_e != null) {
						if (_e.Cancel)
						{
							context = null;
							return;

						}
					}


				CustomerAdapter adapter = _con.GetAdapterObject<CustomerAdapter>(entity);
                adapter.EntityKey = _con.WrappedContext.CreateEntityKey("Customers", adapter);
                
	            //adapter = _con.WrappedContext.AttachObjectGraph<CustomerAdapter>(adapter);
				_con.WrappedContext.AttachTo("Customers", adapter);
                
									_con.WrappedContext.DeleteObject(adapter);
                				
				if (!saveChanges)
                    context = _con.WrappedContext;
                else
                    context = null;
				 SaveOptions saveOption = SaveOptions.None;
                if (saveChanges)
                    saveOption = SaveOptions.AcceptAllChangesAfterSave;

				result = _con.WrappedContext.SaveChanges(saveOption);
				if (saveChanges){
					
					}
				if (_e == null)
					_e = new BusinessRulesEventArgs<Customer>() { Item = entity };
                OnDeleted(this, _e );

				//return null;
			}            
        }
        public void Delete(List<Customer> entities)
        {
				ObjectContext context = null;
			
				foreach (Customer item in entities)
				{
					this.Delete(item, true, out context);
				}
			

			
        }
        #endregion
 
        #region GetCount
        public int GetCount(Expression<Func<Customer, bool>> predicate)
        {
		
			using (EFPocoContext con = new EFPocoContext())
			{


				if (predicate == null) predicate = PredicateBuilder.True<Customer>();
				
				return con.Customers.Count(predicate);
			}

        }
        public int GetCount(string predicate)
        {
			e = null;
            OnCounting(this, e = new BusinessRulesEventArgs<Customer>() {  FilterExpressionString = predicate });
            if (e != null)
            {
                if (e.Cancel)
                {
                    context = null;
                    return e.CountResult;

                }
                predicate = e.FilterExpressionString;
            
            }
					predicate = GetSpecificFilter(predicate);
			using (EFContext con = new EFContext())
			{
				   
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicate, ref predicateWithManyRelations, ref predicateWithFKAndComputed);

                if (!string.IsNullOrEmpty(predicate))
                {
				
					
                    return con.Customers.Count(System.Linq.Dynamic.DynamicExpression.ParseLambda<Customer, bool>(predicate));
					
                }else
                    return con.Customers.Count();

			}

		}
         public int GetCount()
        {
            return GetCount(p => true);
        }
        #endregion
        
         public Customer Update(Customer entity, string paths)
        {
            return Update(entity, paths.Split(char.Parse(",")));
            
        }

        public Customer Update(Customer entity, string[] paths)
        {
            // Translate
            List<Expression<Func<Customer, object>>> pathList = new List<Expression<Func<Customer, object>>>();
            for (int i = 0; i <= paths.Length -1; i++)
            {
                var param = Expression.Parameter(typeof(Customer), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<Customer, object>> path = p => member;
                pathList.Add(path.Expand());
            }
           return Update(entity, pathList.ToArray());
        }

        public void Update(List<Customer> entities, string paths)
        {
            foreach (var entity in entities )
            {
                Update(entity, paths);
            }
        }

        public Customer Create(Customer entity, string paths)
        {
			if(string.IsNullOrEmpty(paths))
				return Create(entity);
				
            return Create(entity, paths.Split(char.Parse(",")));
        }

        public  void Create(List<Customer> entities, string paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }

        public void Create(List<Customer> entities, string[] paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }
        
        public Customer  Create(Customer entity, string[] paths)
        {
            List<Expression<Func<Customer, object>>> pathList = new List<Expression<Func<Customer, object>>>();
            for (int i = 0; i < paths.Length - 1; i++)
            {
                var param = Expression.Parameter(typeof(Customer), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<Customer, object>> path = p => member;
                pathList.Add(path.Expand());
            }
            return Create(entity, pathList.ToArray());
        }
        public void Delete(List<Customer.CompositeKey> entityKeys)
        {

            List<Customer> items = new List<Customer>();
            foreach (var itemKey in entityKeys)
            {
                items.Add(GetByKey(itemKey.CustomerID));
            }

            Delete(items);

        }
		
		
	}
		public partial class CustomerAddressesBR{
	 	
           
		 #region Partial methods

           partial void OnUpdating(object sender, BusinessRulesEventArgs<CustomerAddress> e);

            partial void OnUpdated(object sender, BusinessRulesEventArgs<CustomerAddress> e);

            partial void OnCreating(object sender, BusinessRulesEventArgs<CustomerAddress> e);
            partial void OnCreated(object sender, BusinessRulesEventArgs<CustomerAddress> e);

            partial void OnDeleting(object sender, BusinessRulesEventArgs<CustomerAddress> e);
            partial void OnDeleted(object sender, BusinessRulesEventArgs<CustomerAddress> e);

            partial void OnGetting(object sender, BusinessRulesEventArgs<CustomerAddress> e);
            partial void OnTaken(object sender, BusinessRulesEventArgs<CustomerAddress> e);
            partial void OnCounting(object sender, BusinessRulesEventArgs<CustomerAddress> e);
 
 
            #endregion
			
		private static CustomerAddressesBR singlenton =null;
				public static CustomerAddressesBR NewInstance(){
					return  new CustomerAddressesBR();
					
				}
		public static CustomerAddressesBR Instance{
			get{
				if (singlenton == null)
					singlenton = new CustomerAddressesBR();
				return singlenton;
			}
		}
		private bool preventSecurityRestrictions = false;

		#region Fields
        EFPocoContext context = null;
        #endregion
        #region Constructor
        public CustomerAddressesBR()
        {
            context = new EFPocoContext();
        }
		 public CustomerAddressesBR(bool preventSecurity)
            {
                this.preventSecurityRestrictions = preventSecurity;
				context = new EFPocoContext();
            }
        #endregion
		
		#region Get

 		public IQueryable<CustomerAddress> Get()
        {
            //using (EFContext con = new EFContext())
            //{
				EFContext con = new EFContext();
                var query = con.CustomerAddresses.AsQueryable();
                con.ContextOptions.ProxyCreationEnabled = false;

                //query = ContextQueryBuilder<Nutrient>.ApplyContextQuery(query, contextRequest);

                return query;




            //}

        }
		
		public List<CustomerAddress> GetAll()
        {
            return this.GetBy(p => true);
        }
        public List<CustomerAddress> GetAll(string includes)
        {
            return this.GetBy(p => true, includes);
        }
        public CustomerAddress GetByKey(Int32 customerID, Int32 addressID)
        {
            return GetByKey(customerID, addressID, true);
        }
        public CustomerAddress GetByKey(Int32 customerID, Int32 addressID, bool loadIncludes)
        {
            CustomerAddress item = null;
			var query = PredicateBuilder.True<CustomerAddress>();
                    
			string strWhere = "CustomerID = " + customerID.ToString()+ " And " + "AddressID = " + addressID.ToString();
            Expression<Func<CustomerAddress, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<CustomerAddress, bool>(strWhere);
			
			 ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = strWhere;

			//item = GetBy(predicate, loadIncludes, contextRequest).FirstOrDefault();
			item = GetBy(strWhere,loadIncludes,contextRequest).FirstOrDefault();
            return item;
        }
         public List<CustomerAddress> GetBy(string strWhere, bool loadRelations, ContextRequest contextRequest)
        {
            if (!loadRelations)
                return GetBy(strWhere, contextRequest);
            else
                return GetBy(strWhere, contextRequest, "");

        }
		  public List<CustomerAddress> GetBy(string strWhere, bool loadRelations)
        {
              if (!loadRelations)
                return GetBy(strWhere, new ContextRequest());
            else
                return GetBy(strWhere, new ContextRequest(), "");

        }
         public CustomerAddress GetByKey(Int32 customerID, Int32 addressID, params Expression<Func<CustomerAddress, object>>[] includes)
        {
            CustomerAddress item = null;
			string strWhere = "CustomerID = " + customerID.ToString()+ " And " + "AddressID = " + addressID.ToString();
          Expression<Func<CustomerAddress, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<CustomerAddress, bool>(strWhere);
			
        item = GetBy(predicate, includes).FirstOrDefault();
         ////   item = GetBy(strWhere,includes).FirstOrDefault();
			return item;

        }
        public CustomerAddress GetByKey(Int32 customerID, Int32 addressID, string includes)
        {
            CustomerAddress item = null;
			string strWhere = "CustomerID = " + customerID.ToString()+ " And " + "AddressID = " + addressID.ToString();
            
			
            item = GetBy(strWhere, includes).FirstOrDefault();
            return item;

        }

        #region Dynamic Predicate
        public List<CustomerAddress> GetBy(Expression<Func<CustomerAddress, bool>> predicate, int? pageSize, int? page)
        {
            return this.GetBy(predicate, pageSize, page, null, null);
        }
        public List<CustomerAddress> GetBy(Expression<Func<CustomerAddress, bool>> predicate, ContextRequest contextRequest)
        {

            return GetBy(predicate, contextRequest,"");
        }
        
        public List<CustomerAddress> GetBy(Expression<Func<CustomerAddress, bool>> predicate, ContextRequest contextRequest, params Expression<Func<CustomerAddress, object>>[] includes)
        {
            StringBuilder sb = new StringBuilder();
           if (includes != null)
            {
                foreach (var path in includes)
                {

						if (sb.Length > 0) sb.Append(",");
						sb.Append(SFSdotNet.Framework.Linq.Utils.IncludeToString<CustomerAddress>(path));

               }
            }
            return GetBy(predicate, contextRequest, sb.ToString());
        }
        
        
        public List<CustomerAddress> GetBy(Expression<Func<CustomerAddress, bool>> predicate, string includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";

            return GetBy(predicate, context, includes);
        }

        public List<CustomerAddress> GetBy(Expression<Func<CustomerAddress, bool>> predicate, params Expression<Func<CustomerAddress, object>>[] includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";
            return GetBy(predicate, context, includes);
        }

      
		public bool DisableCache { get; set; }
		 public List<CustomerAddress> GetBy(Expression<Func<CustomerAddress, bool>> predicate, ContextRequest contextRequest, string includes)
        {
            using (EFPocoContext con = new EFPocoContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;

				List<CustomerAddress> result = null;
                 e = null;
                OnGetting(con,e = new BusinessRulesEventArgs<CustomerAddress>() { FilterExpression = predicate, ContextRequest = contextRequest, FilterExpressionString = contextRequest.CustomQuery.FilterExpressionString});
				   if (e != null) {
				    predicate = e.FilterExpression;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				con.EnableChangeTrackingUsingProxies = false;
				con.WrappedContext.CustomerAddresses.MergeOption = MergeOption.NoTracking;
                con.WrappedContext.ContextOptions.ProxyCreationEnabled = false;
                if (predicate == null) predicate = PredicateBuilder.True<CustomerAddress>();
 				string fkIncludes = "Address,Customer";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.CustomerAddresses;
				 
                IQueryable<CustomerAddress> query = es.AsQueryable();

                                if (!string.IsNullOrEmpty(includes))
                {
                    foreach (string include in includes.Split(char.Parse(",")))
                    {
						if (!string.IsNullOrEmpty(include))
                            query = query.Include(include);
                    }
                }
				query =query.Where(predicate);
                query = ContextQueryBuilder<CustomerAddress>.ApplyContextQuery(query, contextRequest);

                result = query.ToList<CustomerAddress>();
				e = null;
				OnTaken(this, e = new BusinessRulesEventArgs<CustomerAddress>() { Items= result, FilterExpression = predicate });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
        public List<CustomerAddress> GetBy(string predicateString, ContextRequest contextRequest, string includes)
        {
            using (EFContext con = new EFContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;


				List<CustomerAddress> result = null;
                 e = null;
                  OnGetting(con,e = new BusinessRulesEventArgs<CustomerAddress>() {  ContextRequest = contextRequest, FilterExpressionString = predicateString });
			   	if (e != null) {
				    predicateString = e.FilterExpressionString;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				//con.EnableChangeTrackingUsingProxies = false;
				con.CustomerAddresses.MergeOption = MergeOption.NoTracking;
                con.ContextOptions.ProxyCreationEnabled = false;
                //if (predicate == null) predicate = PredicateBuilder.True<CustomerAddress>();
 				string fkIncludes = "Address,Customer";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}else{
                    contextRequest = new ContextRequest();
                    contextRequest.CustomQuery = new CustomQuery();

                }
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.CustomerAddresses;
				IQueryable<CustomerAddress> query = es.AsQueryable();

		
				// include relations FK
				if(string.IsNullOrEmpty(includes) ){
					includes ="";
				}
				bool includeAddress = includes.Split(char.Parse(",")).Contains("Address");

				bool includeCustomer = includes.Split(char.Parse(",")).Contains("Customer");

				
				//string predicateString = predicate.ToDynamicLinq<CustomerAddress>();
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicateString, ref predicateWithManyRelations, ref predicateWithFKAndComputed);
                var _queryable = query.AsQueryable();
                if (!string.IsNullOrEmpty(predicateWithManyRelations))
                    _queryable = _queryable.Where(predicateWithManyRelations);
 
				var  queryable = _queryable.Select(                    
				p => 
                        new
                    {
					CustomerID = p.CustomerID
,AddressID = p.AddressID
,AddressType = p.AddressType
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

,Address = includeAddress ? p.Address:null
,Customer = includeCustomer ? p.Customer:null


	
                    }
                    
                    );
					
				
                    if (!string.IsNullOrEmpty(predicateWithFKAndComputed))
                        queryable = queryable.Where(predicateWithFKAndComputed, contextRequest.CustomQuery.ExtraParams);

				QueryComplementOptions queryOps = ContextQueryBuilder.ApplyContextQuery(contextRequest);
            	if (!string.IsNullOrEmpty(queryOps.OrderByAndSort))
					queryable = queryable.OrderBy(queryOps.OrderByAndSort);
               	if (queryOps.Skip != null)
                {
                    queryable = queryable.Skip(queryOps.Skip.Value);
                }
                if (queryOps.PageSize != null)
                {
                    queryable = queryable.Take (queryOps.PageSize.Value);
                }
                result = queryable.AsEnumerable().
                    Select(
                    p =>  new CustomerAddress()
                    {
					CustomerID = p.CustomerID
,AddressID = p.AddressID
,AddressType = p.AddressType
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate
,Address = p.Address
,Customer = p.Customer

                    }
                     ).ToList();

				e = null;
			OnTaken(this, e = new BusinessRulesEventArgs<CustomerAddress>() { Items= result, FilterExpressionString  = predicateString });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
		public List<CustomerAddress> GetBy(Expression<Func<CustomerAddress, bool>> predicate, bool loadRelations, ContextRequest contextRequest)
        {
			if(!loadRelations)
				return GetBy(predicate, contextRequest);
			else
				return GetBy(predicate, contextRequest, "");

        }

        public List<CustomerAddress> GetBy(Expression<Func<CustomerAddress, bool>> predicate, int? pageSize, int? page, string orderBy, SFSdotNet.Framework.Data.SortDirection? sortDirection)
        {
            return GetBy(predicate, new ContextRequest() { CustomQuery = new CustomQuery() { Page = page, PageSize = pageSize, OrderBy = orderBy, SortDirection = sortDirection } });
        }
        public List<CustomerAddress> GetBy(Expression<Func<CustomerAddress, bool>> predicate)
        {
		
			ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = null;
            return this.GetBy(predicate, contextRequest, "");
        }
        #endregion
        #region Dynamic String
		private string GetSpecificFilter(string filter) {
            string result = "";
		    string linqFilter = String.Empty;
            string freeTextFilter = String.Empty;
            if (filter.Contains("|"))
            {
                linqFilter = filter.Split(char.Parse("|"))[0];
                freeTextFilter = filter.Split(char.Parse("|"))[1];
            }
 			else {
                linqFilter = filter;
            }
            string specificFilter = linqFilter;
            if (!string.IsNullOrEmpty(freeTextFilter))
            {
                System.Text.StringBuilder sbCont = new System.Text.StringBuilder();
                if (specificFilter.Length > 0)
                {
                    sbCont.Append(" AND ");
                    sbCont.Append(" ({0})");
                }
                else
                {
                    sbCont.Append("{0}");
                }
                var words = freeTextFilter.Split(char.Parse(" "));
                System.Text.StringBuilder sbSpec = new System.Text.StringBuilder();
                 int nWords = 1;
				foreach (var word in words)
                {
                    if (sbSpec.Length > 0) sbSpec.Append(" AND ");
                    sbSpec.Append("(");
					
	
					
	
					
											
					sbSpec.Append(string.Format(@"AddressType.Contains(""{0}"")", word));

					
	
					
	
					
	
					
	
					
			
                    sbSpec.Append(")");
					
					nWords++;

                }
                specificFilter = string.Format("{0}{1}", specificFilter, string.Format(sbCont.ToString(), sbSpec.ToString()));
            }
			result = specificFilter;
			
			return result;

		}
		public List<CustomerAddress> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params object[] extraParams)
        {
        	string specificFilter = "";
            if (!string.IsNullOrEmpty(filter))
              specificFilter=  GetSpecificFilter(filter);
            if (string.IsNullOrEmpty(orderBy))
            {
			                orderBy = "AddressType";
            }
			SFSdotNet.Framework.Data.SortDirection direction = SFSdotNet.Framework.Data.SortDirection.Ascending;
            if (!string.IsNullOrEmpty(orderDir))
            {
                if (orderDir == "desc")
                    direction = SFSdotNet.Framework.Data.SortDirection.Descending;
            }
            return BR.CustomerAddressesBR.Instance.GetBy(specificFilter,
                new SFSdotNet.Framework.My.ContextRequest()
                {
                    CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
                    {
						ExtraParams= extraParams,
               
                        OrderBy = orderBy,
                        SortDirection = direction,
                        Page = page,
                        PageSize = pageSize
                    }
                });
        }


        public List<CustomerAddress> GetBy(string strWhere, ContextRequest contextRequest)
        {
        	#region old code
				Expression<Func<CustomerAddress, bool>> predicate = null;
                if (!string.IsNullOrEmpty(strWhere)){

                    object[] extraParams = null;
                    if (contextRequest != null )
                        if (contextRequest.CustomQuery != null )
                            extraParams = contextRequest.CustomQuery.ExtraParams;
                    predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<CustomerAddress, bool>(strWhere, extraParams);				}
				 if (contextRequest == null)
                {
                    contextRequest = new ContextRequest();
                    if (contextRequest.CustomQuery == null)
                        contextRequest.CustomQuery = new CustomQuery();
                }
                
            contextRequest.CustomQuery.FilterExpressionString = strWhere;
				//return GetBy(predicate, contextRequest);  

			#endregion				
				
                    return GetBy(strWhere, contextRequest, "");  


        }
       public List<CustomerAddress> GetBy(string strWhere)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
			
            return GetBy(strWhere, context, null);
        }

        public List<CustomerAddress> GetBy(string strWhere, string includes)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
            return GetBy(strWhere, context, includes);
        }

        #endregion
        #endregion
		
		  #region SaveOrUpdate
        private CustomerAddress Save(CustomerAddress entity, bool saveChanges, EFPocoContext con)
        {
				ObjectContext context = null;
            return Update(entity, saveChanges, out context);

			
        }

 		 public CustomerAddress Create(CustomerAddress entity)
        {
				ObjectContext context = null;
				return this.Create(entity, true, out context);

        }
         public CustomerAddress Create(CustomerAddress entity, bool saveChanges, out ObjectContext context)
        {
                    return Create(entity, saveChanges , out context, null);
        }
         public CustomerAddress Create(CustomerAddress entity, params Expression<Func<CustomerAddress,object>>[] paths)
        {
            ObjectContext context = null;
            if(paths != null)
				return Create(entity, true, out context, paths);
			else 
				return Create(entity, true, out context);
        }
        public CustomerAddress Create(CustomerAddress entity, bool saveChanges, out ObjectContext context, params Expression<Func<CustomerAddress,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				CustomerAddress itemResult = null;
#region Autos
	

			entity.rowguid = Guid.NewGuid();
	
	

#endregion
                e = null;
                OnCreating(this,e = new BusinessRulesEventArgs<CustomerAddress>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							context = null;
							return e.Item;

						}
					}



				CustomerAddressAdapter adapter = con.GetAdapterObject<CustomerAddressAdapter>(entity);;
				List<Expression<Func<CustomerAddressAdapter, object>>> paths = new List<Expression<Func<CustomerAddressAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(CustomerAddressAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<CustomerAddressAdapter, object>> path  = null;
                        switch(member.Member.Name){
							
							default:
								path = p => member;
							break;
                        }

                        
                       paths.Add(path.Expand());
                    }
                }
                object aux = null;
					paths.Add(p => p.Address.WithoutUpdate());

					paths.Add(p => p.Customer.WithoutUpdate());

					//paths = pathBuilder.ToArray();

				if (adapter.Address != null ){
					if(adapter.Address.EntityKey == null) adapter.Address.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", adapter.Address);
				}
				if (adapter.Customer != null ){
					if(adapter.Customer.EntityKey == null) adapter.Customer.EntityKey = con.WrappedContext.CreateEntityKey("Customers", adapter.Customer);
				}



                //con.WrappedContext.AttachObjectGraph<CustomerAddressAdapter>(adapter, p=>p.Address, p=>p.Customer);
                con.WrappedContext.AttachObjectGraph<CustomerAddressAdapter>(adapter, paths.ToArray());
              	if (saveChanges){
                    con.WrappedContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
					 
				}
                else
                    con.WrappedContext.SaveChanges(SaveOptions.None);
                if (!saveChanges)
                    context = con.WrappedContext;
                else
                    context = null;
				itemResult = adapter.PocoEntity;
                OnCreated(this, e = new BusinessRulesEventArgs<CustomerAddress>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });
                return itemResult;
            }
        }
        BusinessRulesEventArgs<CustomerAddress> e = null;
        public void Create(List<CustomerAddress> entities)
        {
				ObjectContext context = null;
				foreach (CustomerAddress entity in entities)
				{
					this.Create(entity, true, out context);
				}

				
				
        }

        public CustomerAddress Update(CustomerAddress entity)
        {
			ObjectContext context = null;
            return Update(entity, true, out context, null);

        }
         public CustomerAddress Update(CustomerAddress entity, params Expression<Func<CustomerAddress, object>>[] paths)
        {
			  ObjectContext context = null;
            return Update(entity, true, out context, paths);
         }
        public CustomerAddress Update(CustomerAddress entity, bool saveChanges, out ObjectContext outcontext)
        {
			return Update(entity, saveChanges, out outcontext, null);
		}
         public CustomerAddress Update(CustomerAddress entity, bool saveChanges, out ObjectContext outcontext, params Expression<Func<CustomerAddress,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				CustomerAddress  itemResult = null;

	

				e = null;
                OnUpdating(this,e = new BusinessRulesEventArgs<CustomerAddress>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							outcontext = null;
							return e.Item;

						}
					}

                CustomerAddressAdapter adapter = con.GetAdapterObject<CustomerAddressAdapter>(entity);
                adapter.EntityKey = con.WrappedContext.CreateEntityKey("CustomerAddresses", adapter);
				    var es = con.CustomerAddresses;
				List<Expression<Func<CustomerAddressAdapter, object>>> paths = new List<Expression<Func<CustomerAddressAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(CustomerAddressAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<CustomerAddressAdapter, object>> path  = null;
                        switch(member.Member.Name){
							
							default:
								path = p => member;
							break;
                        }

                        paths.Add(path.Expand());
 					}
                }
                else {
                  paths = new List<Expression<Func<CustomerAddressAdapter, object>>>();

					//List<Expression<Func<CustomerAddressAdapter,object>>> pathBuilder = new List<Expression<Func<CustomerAddressAdapter,object>>>();
					paths.Add(p => p.Address.WithoutUpdate());

					paths.Add(p => p.Customer.WithoutUpdate());

		
					//paths = pathBuilder.ToArray();		
			}
			object aux = null;
				if (adapter.Address != null ){
					if(adapter.Address.EntityKey == null) adapter.Address.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", adapter.Address);
				}

                
				if (adapter.Customer != null ){
					if(adapter.Customer.EntityKey == null) adapter.Customer.EntityKey = con.WrappedContext.CreateEntityKey("Customers", adapter.Customer);
				}

                



                //con.AttachObjectGraph<CustomerAddress>(adapter, p=>p.Address, p=>p.Customer);
                con.WrappedContext.AttachObjectGraph<CustomerAddressAdapter>(adapter, paths.ToArray());
				if (saveChanges){
                	con.WrappedContext.SaveChanges();
					 
					}
                if(!saveChanges)
					outcontext = con.WrappedContext;
				else
					outcontext = null;
				itemResult = adapter.PocoEntity;
				OnUpdated(this, e = new BusinessRulesEventArgs<CustomerAddress>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });

              	return itemResult;

			  }
        }
        public CustomerAddress Save(CustomerAddress entity)
        {
			return Save(entity, true, null);
        }
        public int Save(List<CustomerAddress> entities)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
			
            int n = 0;
            foreach (CustomerAddress item in entities)
            {
                try
                {
                    this.Save(item, false, con);
                    n++;
                }catch (Exception ex){
                    SFSdotNet.Framework.My.EventLog.Exception(ex);
                }
            }
            con.SaveChanges();
            return n;
            }
        }
        #endregion
        #region Delete
        public void Delete(CustomerAddress entity)
        {
				ObjectContext context = null;
				this.Delete(entity, true, out context);
			
        }

        
        public void Delete(CustomerAddress entity, bool saveChanges, out  ObjectContext context)
        {
			using (EFPocoContext _con = new EFPocoContext())
			{
				int result = 0;
				
               	BusinessRulesEventArgs<CustomerAddress> _e = null;
                OnDeleting(this,_e = new BusinessRulesEventArgs<CustomerAddress>() { Item=entity, SaveChanges =saveChanges });
				   if (_e != null) {
						if (_e.Cancel)
						{
							context = null;
							return;

						}
					}


				CustomerAddressAdapter adapter = _con.GetAdapterObject<CustomerAddressAdapter>(entity);
                adapter.EntityKey = _con.WrappedContext.CreateEntityKey("CustomerAddresses", adapter);
                
	            //adapter = _con.WrappedContext.AttachObjectGraph<CustomerAddressAdapter>(adapter);
				_con.WrappedContext.AttachTo("CustomerAddresses", adapter);
                
									_con.WrappedContext.DeleteObject(adapter);
                				
				if (!saveChanges)
                    context = _con.WrappedContext;
                else
                    context = null;
				 SaveOptions saveOption = SaveOptions.None;
                if (saveChanges)
                    saveOption = SaveOptions.AcceptAllChangesAfterSave;

				result = _con.WrappedContext.SaveChanges(saveOption);
				if (saveChanges){
					
					}
				if (_e == null)
					_e = new BusinessRulesEventArgs<CustomerAddress>() { Item = entity };
                OnDeleted(this, _e );

				//return null;
			}            
        }
        public void Delete(List<CustomerAddress> entities)
        {
				ObjectContext context = null;
			
				foreach (CustomerAddress item in entities)
				{
					this.Delete(item, true, out context);
				}
			

			
        }
        #endregion
 
        #region GetCount
        public int GetCount(Expression<Func<CustomerAddress, bool>> predicate)
        {
		
			using (EFPocoContext con = new EFPocoContext())
			{


				if (predicate == null) predicate = PredicateBuilder.True<CustomerAddress>();
				
				return con.CustomerAddresses.Count(predicate);
			}

        }
        public int GetCount(string predicate)
        {
			e = null;
            OnCounting(this, e = new BusinessRulesEventArgs<CustomerAddress>() {  FilterExpressionString = predicate });
            if (e != null)
            {
                if (e.Cancel)
                {
                    context = null;
                    return e.CountResult;

                }
                predicate = e.FilterExpressionString;
            
            }
					predicate = GetSpecificFilter(predicate);
			using (EFContext con = new EFContext())
			{
				   
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicate, ref predicateWithManyRelations, ref predicateWithFKAndComputed);

                if (!string.IsNullOrEmpty(predicate))
                {
				
					
                    return con.CustomerAddresses.Count(System.Linq.Dynamic.DynamicExpression.ParseLambda<CustomerAddress, bool>(predicate));
					
                }else
                    return con.CustomerAddresses.Count();

			}

		}
         public int GetCount()
        {
            return GetCount(p => true);
        }
        #endregion
        
         public CustomerAddress Update(CustomerAddress entity, string paths)
        {
            return Update(entity, paths.Split(char.Parse(",")));
            
        }

        public CustomerAddress Update(CustomerAddress entity, string[] paths)
        {
            // Translate
            List<Expression<Func<CustomerAddress, object>>> pathList = new List<Expression<Func<CustomerAddress, object>>>();
            for (int i = 0; i <= paths.Length -1; i++)
            {
                var param = Expression.Parameter(typeof(CustomerAddress), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<CustomerAddress, object>> path = p => member;
                pathList.Add(path.Expand());
            }
           return Update(entity, pathList.ToArray());
        }

        public void Update(List<CustomerAddress> entities, string paths)
        {
            foreach (var entity in entities )
            {
                Update(entity, paths);
            }
        }

        public CustomerAddress Create(CustomerAddress entity, string paths)
        {
			if(string.IsNullOrEmpty(paths))
				return Create(entity);
				
            return Create(entity, paths.Split(char.Parse(",")));
        }

        public  void Create(List<CustomerAddress> entities, string paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }

        public void Create(List<CustomerAddress> entities, string[] paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }
        
        public CustomerAddress  Create(CustomerAddress entity, string[] paths)
        {
            List<Expression<Func<CustomerAddress, object>>> pathList = new List<Expression<Func<CustomerAddress, object>>>();
            for (int i = 0; i < paths.Length - 1; i++)
            {
                var param = Expression.Parameter(typeof(CustomerAddress), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<CustomerAddress, object>> path = p => member;
                pathList.Add(path.Expand());
            }
            return Create(entity, pathList.ToArray());
        }
        public void Delete(List<CustomerAddress.CompositeKey> entityKeys)
        {

            List<CustomerAddress> items = new List<CustomerAddress>();
            foreach (var itemKey in entityKeys)
            {
                items.Add(GetByKey(itemKey.CustomerID, itemKey.AddressID));
            }

            Delete(items);

        }
		
		
	}
		public partial class ProductsBR{
	 	
           
		 #region Partial methods

           partial void OnUpdating(object sender, BusinessRulesEventArgs<Product> e);

            partial void OnUpdated(object sender, BusinessRulesEventArgs<Product> e);

            partial void OnCreating(object sender, BusinessRulesEventArgs<Product> e);
            partial void OnCreated(object sender, BusinessRulesEventArgs<Product> e);

            partial void OnDeleting(object sender, BusinessRulesEventArgs<Product> e);
            partial void OnDeleted(object sender, BusinessRulesEventArgs<Product> e);

            partial void OnGetting(object sender, BusinessRulesEventArgs<Product> e);
            partial void OnTaken(object sender, BusinessRulesEventArgs<Product> e);
            partial void OnCounting(object sender, BusinessRulesEventArgs<Product> e);
 
 
            #endregion
			
		private static ProductsBR singlenton =null;
				public static ProductsBR NewInstance(){
					return  new ProductsBR();
					
				}
		public static ProductsBR Instance{
			get{
				if (singlenton == null)
					singlenton = new ProductsBR();
				return singlenton;
			}
		}
		private bool preventSecurityRestrictions = false;

		#region Fields
        EFPocoContext context = null;
        #endregion
        #region Constructor
        public ProductsBR()
        {
            context = new EFPocoContext();
        }
		 public ProductsBR(bool preventSecurity)
            {
                this.preventSecurityRestrictions = preventSecurity;
				context = new EFPocoContext();
            }
        #endregion
		
		#region Get

 		public IQueryable<Product> Get()
        {
            //using (EFContext con = new EFContext())
            //{
				EFContext con = new EFContext();
                var query = con.Products.AsQueryable();
                con.ContextOptions.ProxyCreationEnabled = false;

                //query = ContextQueryBuilder<Nutrient>.ApplyContextQuery(query, contextRequest);

                return query;




            //}

        }
		
		public List<Product> GetAll()
        {
            return this.GetBy(p => true);
        }
        public List<Product> GetAll(string includes)
        {
            return this.GetBy(p => true, includes);
        }
        public Product GetByKey(Int32 productID)
        {
            return GetByKey(productID, true);
        }
        public Product GetByKey(Int32 productID, bool loadIncludes)
        {
            Product item = null;
			var query = PredicateBuilder.True<Product>();
                    
			string strWhere = "ProductID = " + productID.ToString();
            Expression<Func<Product, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<Product, bool>(strWhere);
			
			 ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = strWhere;

			//item = GetBy(predicate, loadIncludes, contextRequest).FirstOrDefault();
			item = GetBy(strWhere,loadIncludes,contextRequest).FirstOrDefault();
            return item;
        }
         public List<Product> GetBy(string strWhere, bool loadRelations, ContextRequest contextRequest)
        {
            if (!loadRelations)
                return GetBy(strWhere, contextRequest);
            else
                return GetBy(strWhere, contextRequest, "");

        }
		  public List<Product> GetBy(string strWhere, bool loadRelations)
        {
              if (!loadRelations)
                return GetBy(strWhere, new ContextRequest());
            else
                return GetBy(strWhere, new ContextRequest(), "");

        }
         public Product GetByKey(Int32 productID, params Expression<Func<Product, object>>[] includes)
        {
            Product item = null;
			string strWhere = "ProductID = " + productID.ToString();
          Expression<Func<Product, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<Product, bool>(strWhere);
			
        item = GetBy(predicate, includes).FirstOrDefault();
         ////   item = GetBy(strWhere,includes).FirstOrDefault();
			return item;

        }
        public Product GetByKey(Int32 productID, string includes)
        {
            Product item = null;
			string strWhere = "ProductID = " + productID.ToString();
            
			
            item = GetBy(strWhere, includes).FirstOrDefault();
            return item;

        }

        #region Dynamic Predicate
        public List<Product> GetBy(Expression<Func<Product, bool>> predicate, int? pageSize, int? page)
        {
            return this.GetBy(predicate, pageSize, page, null, null);
        }
        public List<Product> GetBy(Expression<Func<Product, bool>> predicate, ContextRequest contextRequest)
        {

            return GetBy(predicate, contextRequest,"");
        }
        
        public List<Product> GetBy(Expression<Func<Product, bool>> predicate, ContextRequest contextRequest, params Expression<Func<Product, object>>[] includes)
        {
            StringBuilder sb = new StringBuilder();
           if (includes != null)
            {
                foreach (var path in includes)
                {

						if (sb.Length > 0) sb.Append(",");
						sb.Append(SFSdotNet.Framework.Linq.Utils.IncludeToString<Product>(path));

               }
            }
            return GetBy(predicate, contextRequest, sb.ToString());
        }
        
        
        public List<Product> GetBy(Expression<Func<Product, bool>> predicate, string includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";

            return GetBy(predicate, context, includes);
        }

        public List<Product> GetBy(Expression<Func<Product, bool>> predicate, params Expression<Func<Product, object>>[] includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";
            return GetBy(predicate, context, includes);
        }

      
		public bool DisableCache { get; set; }
		 public List<Product> GetBy(Expression<Func<Product, bool>> predicate, ContextRequest contextRequest, string includes)
        {
            using (EFPocoContext con = new EFPocoContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;

				List<Product> result = null;
                 e = null;
                OnGetting(con,e = new BusinessRulesEventArgs<Product>() { FilterExpression = predicate, ContextRequest = contextRequest, FilterExpressionString = contextRequest.CustomQuery.FilterExpressionString});
				   if (e != null) {
				    predicate = e.FilterExpression;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				con.EnableChangeTrackingUsingProxies = false;
				con.WrappedContext.Products.MergeOption = MergeOption.NoTracking;
                con.WrappedContext.ContextOptions.ProxyCreationEnabled = false;
                if (predicate == null) predicate = PredicateBuilder.True<Product>();
 				string fkIncludes = "ProductCategory,ProductModel";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.Products;
				 
                IQueryable<Product> query = es.AsQueryable();

                                if (!string.IsNullOrEmpty(includes))
                {
                    foreach (string include in includes.Split(char.Parse(",")))
                    {
						if (!string.IsNullOrEmpty(include))
                            query = query.Include(include);
                    }
                }
				query =query.Where(predicate);
                query = ContextQueryBuilder<Product>.ApplyContextQuery(query, contextRequest);

                result = query.ToList<Product>();
				e = null;
				OnTaken(this, e = new BusinessRulesEventArgs<Product>() { Items= result, FilterExpression = predicate });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
        public List<Product> GetBy(string predicateString, ContextRequest contextRequest, string includes)
        {
            using (EFContext con = new EFContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;


				List<Product> result = null;
                 e = null;
                  OnGetting(con,e = new BusinessRulesEventArgs<Product>() {  ContextRequest = contextRequest, FilterExpressionString = predicateString });
			   	if (e != null) {
				    predicateString = e.FilterExpressionString;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				//con.EnableChangeTrackingUsingProxies = false;
				con.Products.MergeOption = MergeOption.NoTracking;
                con.ContextOptions.ProxyCreationEnabled = false;
                //if (predicate == null) predicate = PredicateBuilder.True<Product>();
 				string fkIncludes = "ProductCategory,ProductModel";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}else{
                    contextRequest = new ContextRequest();
                    contextRequest.CustomQuery = new CustomQuery();

                }
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.Products;
				IQueryable<Product> query = es.AsQueryable();

		
				// include relations FK
				if(string.IsNullOrEmpty(includes) ){
					includes ="";
				}
				bool includeThumbNailPhoto = includes.Split(char.Parse(",")).Contains("ThumbNailPhoto");

				bool includeProductCategory = includes.Split(char.Parse(",")).Contains("ProductCategory");

				bool includeProductModel = includes.Split(char.Parse(",")).Contains("ProductModel");

				
				//string predicateString = predicate.ToDynamicLinq<Product>();
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicateString, ref predicateWithManyRelations, ref predicateWithFKAndComputed);
                var _queryable = query.AsQueryable();
                if (!string.IsNullOrEmpty(predicateWithManyRelations))
                    _queryable = _queryable.Where(predicateWithManyRelations);
 
				var  queryable = _queryable.Select(                    
				p => 
                        new
                    {
					ProductID = p.ProductID
,Name = p.Name
,ProductNumber = p.ProductNumber
,Color = p.Color
,StandardCost = p.StandardCost
,ListPrice = p.ListPrice
,Size = p.Size
,Weight = p.Weight
,SellStartDate = p.SellStartDate
,SellEndDate = p.SellEndDate
,DiscontinuedDate = p.DiscontinuedDate
,ThumbnailPhotoFileName = p.ThumbnailPhotoFileName
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

,ThumbNailPhoto = includeThumbNailPhoto ? p.ThumbNailPhoto:null
,ProductCategory = includeProductCategory ? p.ProductCategory:null
,ProductModel = includeProductModel ? p.ProductModel:null


	
                    }
                    
                    );
					
				
                    if (!string.IsNullOrEmpty(predicateWithFKAndComputed))
                        queryable = queryable.Where(predicateWithFKAndComputed, contextRequest.CustomQuery.ExtraParams);

				QueryComplementOptions queryOps = ContextQueryBuilder.ApplyContextQuery(contextRequest);
            	if (!string.IsNullOrEmpty(queryOps.OrderByAndSort))
					queryable = queryable.OrderBy(queryOps.OrderByAndSort);
               	if (queryOps.Skip != null)
                {
                    queryable = queryable.Skip(queryOps.Skip.Value);
                }
                if (queryOps.PageSize != null)
                {
                    queryable = queryable.Take (queryOps.PageSize.Value);
                }
                result = queryable.AsEnumerable().
                    Select(
                    p =>  new Product()
                    {
					ProductID = p.ProductID
,Name = p.Name
,ProductNumber = p.ProductNumber
,Color = p.Color
,StandardCost = p.StandardCost
,ListPrice = p.ListPrice
,Size = p.Size
,Weight = p.Weight
,SellStartDate = p.SellStartDate
,SellEndDate = p.SellEndDate
,DiscontinuedDate = p.DiscontinuedDate
,ThumbNailPhoto = p.ThumbNailPhoto
,ThumbnailPhotoFileName = p.ThumbnailPhotoFileName
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate
,ProductCategory = p.ProductCategory
,ProductModel = p.ProductModel

                    }
                     ).ToList();

				e = null;
			OnTaken(this, e = new BusinessRulesEventArgs<Product>() { Items= result, FilterExpressionString  = predicateString });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
		public List<Product> GetBy(Expression<Func<Product, bool>> predicate, bool loadRelations, ContextRequest contextRequest)
        {
			if(!loadRelations)
				return GetBy(predicate, contextRequest);
			else
				return GetBy(predicate, contextRequest, "SalesOrderDetails");

        }

        public List<Product> GetBy(Expression<Func<Product, bool>> predicate, int? pageSize, int? page, string orderBy, SFSdotNet.Framework.Data.SortDirection? sortDirection)
        {
            return GetBy(predicate, new ContextRequest() { CustomQuery = new CustomQuery() { Page = page, PageSize = pageSize, OrderBy = orderBy, SortDirection = sortDirection } });
        }
        public List<Product> GetBy(Expression<Func<Product, bool>> predicate)
        {
		
			ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = null;
            return this.GetBy(predicate, contextRequest, "");
        }
        #endregion
        #region Dynamic String
		private string GetSpecificFilter(string filter) {
            string result = "";
		    string linqFilter = String.Empty;
            string freeTextFilter = String.Empty;
            if (filter.Contains("|"))
            {
                linqFilter = filter.Split(char.Parse("|"))[0];
                freeTextFilter = filter.Split(char.Parse("|"))[1];
            }
 			else {
                linqFilter = filter;
            }
            string specificFilter = linqFilter;
            if (!string.IsNullOrEmpty(freeTextFilter))
            {
                System.Text.StringBuilder sbCont = new System.Text.StringBuilder();
                if (specificFilter.Length > 0)
                {
                    sbCont.Append(" AND ");
                    sbCont.Append(" ({0})");
                }
                else
                {
                    sbCont.Append("{0}");
                }
                var words = freeTextFilter.Split(char.Parse(" "));
                System.Text.StringBuilder sbSpec = new System.Text.StringBuilder();
                 int nWords = 1;
				foreach (var word in words)
                {
                    if (sbSpec.Length > 0) sbSpec.Append(" AND ");
                    sbSpec.Append("(");
					
	
					
											
					sbSpec.Append(string.Format(@"Name.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"ProductNumber.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"Color.Contains(""{0}"")", word));

					
	
					
	
					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"Size.Contains(""{0}"")", word));

					
	
					
	
					
	
					
	
					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"ThumbnailPhotoFileName.Contains(""{0}"")", word));

					
	
					
	
					
	
					
	
					
			
                    sbSpec.Append(")");
					
					nWords++;

                }
                specificFilter = string.Format("{0}{1}", specificFilter, string.Format(sbCont.ToString(), sbSpec.ToString()));
            }
			result = specificFilter;
			
			return result;

		}
		public List<Product> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params object[] extraParams)
        {
        	string specificFilter = "";
            if (!string.IsNullOrEmpty(filter))
              specificFilter=  GetSpecificFilter(filter);
            if (string.IsNullOrEmpty(orderBy))
            {
			                orderBy = "Name";
            }
			SFSdotNet.Framework.Data.SortDirection direction = SFSdotNet.Framework.Data.SortDirection.Ascending;
            if (!string.IsNullOrEmpty(orderDir))
            {
                if (orderDir == "desc")
                    direction = SFSdotNet.Framework.Data.SortDirection.Descending;
            }
            return BR.ProductsBR.Instance.GetBy(specificFilter,
                new SFSdotNet.Framework.My.ContextRequest()
                {
                    CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
                    {
						ExtraParams= extraParams,
               
                        OrderBy = orderBy,
                        SortDirection = direction,
                        Page = page,
                        PageSize = pageSize
                    }
                });
        }


        public List<Product> GetBy(string strWhere, ContextRequest contextRequest)
        {
        	#region old code
				Expression<Func<Product, bool>> predicate = null;
                if (!string.IsNullOrEmpty(strWhere)){

                    object[] extraParams = null;
                    if (contextRequest != null )
                        if (contextRequest.CustomQuery != null )
                            extraParams = contextRequest.CustomQuery.ExtraParams;
                    predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<Product, bool>(strWhere, extraParams);				}
				 if (contextRequest == null)
                {
                    contextRequest = new ContextRequest();
                    if (contextRequest.CustomQuery == null)
                        contextRequest.CustomQuery = new CustomQuery();
                }
                
            contextRequest.CustomQuery.FilterExpressionString = strWhere;
				//return GetBy(predicate, contextRequest);  

			#endregion				
				
                    return GetBy(strWhere, contextRequest, "");  


        }
       public List<Product> GetBy(string strWhere)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
			
            return GetBy(strWhere, context, null);
        }

        public List<Product> GetBy(string strWhere, string includes)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
            return GetBy(strWhere, context, includes);
        }

        #endregion
        #endregion
		
		  #region SaveOrUpdate
        private Product Save(Product entity, bool saveChanges, EFPocoContext con)
        {
				ObjectContext context = null;
            return Update(entity, saveChanges, out context);

			
        }

 		 public Product Create(Product entity)
        {
				ObjectContext context = null;
				return this.Create(entity, true, out context);

        }
         public Product Create(Product entity, bool saveChanges, out ObjectContext context)
        {
                    return Create(entity, saveChanges , out context, null);
        }
         public Product Create(Product entity, params Expression<Func<Product,object>>[] paths)
        {
            ObjectContext context = null;
            if(paths != null)
				return Create(entity, true, out context, paths);
			else 
				return Create(entity, true, out context);
        }
        public Product Create(Product entity, bool saveChanges, out ObjectContext context, params Expression<Func<Product,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				Product itemResult = null;
#region Autos
	

			entity.rowguid = Guid.NewGuid();
	
	

#endregion
                e = null;
                OnCreating(this,e = new BusinessRulesEventArgs<Product>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							context = null;
							return e.Item;

						}
					}



				ProductAdapter adapter = con.GetAdapterObject<ProductAdapter>(entity);;
				List<Expression<Func<ProductAdapter, object>>> paths = new List<Expression<Func<ProductAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(ProductAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<ProductAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "SalesOrderDetails":
								path = p => p.SalesOrderDetails.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.SalesOrderDetails.First().SalesOrderHeader.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        
                       paths.Add(path.Expand());
                    }
                }
                object aux = null;
					paths.Add(p => p.ProductCategory.WithoutUpdate());

					paths.Add(p => p.ProductModel.WithoutUpdate());

					//paths = pathBuilder.ToArray();

				if (adapter.ProductCategory != null ){
					if(adapter.ProductCategory.EntityKey == null) adapter.ProductCategory.EntityKey = con.WrappedContext.CreateEntityKey("ProductCategories", adapter.ProductCategory);
				}
				if (adapter.ProductModel != null ){
					if(adapter.ProductModel.EntityKey == null) adapter.ProductModel.EntityKey = con.WrappedContext.CreateEntityKey("ProductModels", adapter.ProductModel);
				}
#region Childs SalesOrderDetails 
				if (adapter.SalesOrderDetails != null)
                {
                    foreach (var item in adapter.SalesOrderDetails)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderDetails", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.SalesOrderDetails.First().WithoutUpdate());
								
							if (item.Product == null)
								item.Product = adapter;

						if (item.SalesOrderHeader != null){
							item.SalesOrderHeader.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderHeaders", item.SalesOrderHeader);
                            
             
						}								
								item.EntityKey = null;
							}

                    }
					if (adapter.SalesOrderDetails.Count > 0){
						paths.Add(p => p.SalesOrderDetails.First().WithoutUpdate());
						paths.Add(p => p.SalesOrderDetails.First().SalesOrderHeader.WithoutUpdate());
					
					}
                }
#endregion 




                //con.WrappedContext.AttachObjectGraph<ProductAdapter>(adapter, p=>p.ProductCategory, p=>p.ProductModel, p=>p.SalesOrderDetails);
                con.WrappedContext.AttachObjectGraph<ProductAdapter>(adapter, paths.ToArray());
              	if (saveChanges){
                    con.WrappedContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
					 
				}
                else
                    con.WrappedContext.SaveChanges(SaveOptions.None);
                if (!saveChanges)
                    context = con.WrappedContext;
                else
                    context = null;
				itemResult = adapter.PocoEntity;
                OnCreated(this, e = new BusinessRulesEventArgs<Product>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });
                return itemResult;
            }
        }
        BusinessRulesEventArgs<Product> e = null;
        public void Create(List<Product> entities)
        {
				ObjectContext context = null;
				foreach (Product entity in entities)
				{
					this.Create(entity, true, out context);
				}

				
				
        }

        public Product Update(Product entity)
        {
			ObjectContext context = null;
            return Update(entity, true, out context, null);

        }
         public Product Update(Product entity, params Expression<Func<Product, object>>[] paths)
        {
			  ObjectContext context = null;
            return Update(entity, true, out context, paths);
         }
        public Product Update(Product entity, bool saveChanges, out ObjectContext outcontext)
        {
			return Update(entity, saveChanges, out outcontext, null);
		}
         public Product Update(Product entity, bool saveChanges, out ObjectContext outcontext, params Expression<Func<Product,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				Product  itemResult = null;

	

				e = null;
                OnUpdating(this,e = new BusinessRulesEventArgs<Product>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							outcontext = null;
							return e.Item;

						}
					}

                ProductAdapter adapter = con.GetAdapterObject<ProductAdapter>(entity);
                adapter.EntityKey = con.WrappedContext.CreateEntityKey("Products", adapter);
				    var es = con.Products;
				List<Expression<Func<ProductAdapter, object>>> paths = new List<Expression<Func<ProductAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(ProductAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<ProductAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "SalesOrderDetails":
								//path = p => member;
								path = p => p.SalesOrderDetails.First().WithoutUpdate();
				//				path = p => p.SalesOrderDetails.First().SalesOrderHeader.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        paths.Add(path.Expand());
 					}
                }
                else {
                  paths = new List<Expression<Func<ProductAdapter, object>>>();

					//List<Expression<Func<ProductAdapter,object>>> pathBuilder = new List<Expression<Func<ProductAdapter,object>>>();
					paths.Add(p => p.ProductCategory.WithoutUpdate());

					paths.Add(p => p.ProductModel.WithoutUpdate());

		
					//paths = pathBuilder.ToArray();		
			}
			object aux = null;
				if (adapter.ProductCategory != null ){
					if(adapter.ProductCategory.EntityKey == null) adapter.ProductCategory.EntityKey = con.WrappedContext.CreateEntityKey("ProductCategories", adapter.ProductCategory);
				}

                
				if (adapter.ProductModel != null ){
					if(adapter.ProductModel.EntityKey == null) adapter.ProductModel.EntityKey = con.WrappedContext.CreateEntityKey("ProductModels", adapter.ProductModel);
				}

                
				if (adapter.SalesOrderDetails != null)
                {
                    foreach (var item in adapter.SalesOrderDetails)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderDetails", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }



                //con.AttachObjectGraph<Product>(adapter, p=>p.ProductCategory, p=>p.ProductModel, p=>p.SalesOrderDetails);
                con.WrappedContext.AttachObjectGraph<ProductAdapter>(adapter, paths.ToArray());
				if (saveChanges){
                	con.WrappedContext.SaveChanges();
					 
					}
                if(!saveChanges)
					outcontext = con.WrappedContext;
				else
					outcontext = null;
				itemResult = adapter.PocoEntity;
				OnUpdated(this, e = new BusinessRulesEventArgs<Product>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });

              	return itemResult;

			  }
        }
        public Product Save(Product entity)
        {
			return Save(entity, true, null);
        }
        public int Save(List<Product> entities)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
			
            int n = 0;
            foreach (Product item in entities)
            {
                try
                {
                    this.Save(item, false, con);
                    n++;
                }catch (Exception ex){
                    SFSdotNet.Framework.My.EventLog.Exception(ex);
                }
            }
            con.SaveChanges();
            return n;
            }
        }
        #endregion
        #region Delete
        public void Delete(Product entity)
        {
				ObjectContext context = null;
				this.Delete(entity, true, out context);
			
        }

        
        public void Delete(Product entity, bool saveChanges, out  ObjectContext context)
        {
			using (EFPocoContext _con = new EFPocoContext())
			{
				int result = 0;
				
               	BusinessRulesEventArgs<Product> _e = null;
                OnDeleting(this,_e = new BusinessRulesEventArgs<Product>() { Item=entity, SaveChanges =saveChanges });
				   if (_e != null) {
						if (_e.Cancel)
						{
							context = null;
							return;

						}
					}


				ProductAdapter adapter = _con.GetAdapterObject<ProductAdapter>(entity);
                adapter.EntityKey = _con.WrappedContext.CreateEntityKey("Products", adapter);
                
	            //adapter = _con.WrappedContext.AttachObjectGraph<ProductAdapter>(adapter);
				_con.WrappedContext.AttachTo("Products", adapter);
                
									_con.WrappedContext.DeleteObject(adapter);
                				
				if (!saveChanges)
                    context = _con.WrappedContext;
                else
                    context = null;
				 SaveOptions saveOption = SaveOptions.None;
                if (saveChanges)
                    saveOption = SaveOptions.AcceptAllChangesAfterSave;

				result = _con.WrappedContext.SaveChanges(saveOption);
				if (saveChanges){
					
					}
				if (_e == null)
					_e = new BusinessRulesEventArgs<Product>() { Item = entity };
                OnDeleted(this, _e );

				//return null;
			}            
        }
        public void Delete(List<Product> entities)
        {
				ObjectContext context = null;
			
				foreach (Product item in entities)
				{
					this.Delete(item, true, out context);
				}
			

			
        }
        #endregion
 
        #region GetCount
        public int GetCount(Expression<Func<Product, bool>> predicate)
        {
		
			using (EFPocoContext con = new EFPocoContext())
			{


				if (predicate == null) predicate = PredicateBuilder.True<Product>();
				
				return con.Products.Count(predicate);
			}

        }
        public int GetCount(string predicate)
        {
			e = null;
            OnCounting(this, e = new BusinessRulesEventArgs<Product>() {  FilterExpressionString = predicate });
            if (e != null)
            {
                if (e.Cancel)
                {
                    context = null;
                    return e.CountResult;

                }
                predicate = e.FilterExpressionString;
            
            }
					predicate = GetSpecificFilter(predicate);
			using (EFContext con = new EFContext())
			{
				   
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicate, ref predicateWithManyRelations, ref predicateWithFKAndComputed);

                if (!string.IsNullOrEmpty(predicate))
                {
				
					
                    return con.Products.Count(System.Linq.Dynamic.DynamicExpression.ParseLambda<Product, bool>(predicate));
					
                }else
                    return con.Products.Count();

			}

		}
         public int GetCount()
        {
            return GetCount(p => true);
        }
        #endregion
        
         public Product Update(Product entity, string paths)
        {
            return Update(entity, paths.Split(char.Parse(",")));
            
        }

        public Product Update(Product entity, string[] paths)
        {
            // Translate
            List<Expression<Func<Product, object>>> pathList = new List<Expression<Func<Product, object>>>();
            for (int i = 0; i <= paths.Length -1; i++)
            {
                var param = Expression.Parameter(typeof(Product), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<Product, object>> path = p => member;
                pathList.Add(path.Expand());
            }
           return Update(entity, pathList.ToArray());
        }

        public void Update(List<Product> entities, string paths)
        {
            foreach (var entity in entities )
            {
                Update(entity, paths);
            }
        }

        public Product Create(Product entity, string paths)
        {
			if(string.IsNullOrEmpty(paths))
				return Create(entity);
				
            return Create(entity, paths.Split(char.Parse(",")));
        }

        public  void Create(List<Product> entities, string paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }

        public void Create(List<Product> entities, string[] paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }
        
        public Product  Create(Product entity, string[] paths)
        {
            List<Expression<Func<Product, object>>> pathList = new List<Expression<Func<Product, object>>>();
            for (int i = 0; i < paths.Length - 1; i++)
            {
                var param = Expression.Parameter(typeof(Product), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<Product, object>> path = p => member;
                pathList.Add(path.Expand());
            }
            return Create(entity, pathList.ToArray());
        }
        public void Delete(List<Product.CompositeKey> entityKeys)
        {

            List<Product> items = new List<Product>();
            foreach (var itemKey in entityKeys)
            {
                items.Add(GetByKey(itemKey.ProductID));
            }

            Delete(items);

        }
		
		
	}
		public partial class ProductCategoriesBR{
	 	
           
		 #region Partial methods

           partial void OnUpdating(object sender, BusinessRulesEventArgs<ProductCategory> e);

            partial void OnUpdated(object sender, BusinessRulesEventArgs<ProductCategory> e);

            partial void OnCreating(object sender, BusinessRulesEventArgs<ProductCategory> e);
            partial void OnCreated(object sender, BusinessRulesEventArgs<ProductCategory> e);

            partial void OnDeleting(object sender, BusinessRulesEventArgs<ProductCategory> e);
            partial void OnDeleted(object sender, BusinessRulesEventArgs<ProductCategory> e);

            partial void OnGetting(object sender, BusinessRulesEventArgs<ProductCategory> e);
            partial void OnTaken(object sender, BusinessRulesEventArgs<ProductCategory> e);
            partial void OnCounting(object sender, BusinessRulesEventArgs<ProductCategory> e);
 
 
            #endregion
			
		private static ProductCategoriesBR singlenton =null;
				public static ProductCategoriesBR NewInstance(){
					return  new ProductCategoriesBR();
					
				}
		public static ProductCategoriesBR Instance{
			get{
				if (singlenton == null)
					singlenton = new ProductCategoriesBR();
				return singlenton;
			}
		}
		private bool preventSecurityRestrictions = false;

		#region Fields
        EFPocoContext context = null;
        #endregion
        #region Constructor
        public ProductCategoriesBR()
        {
            context = new EFPocoContext();
        }
		 public ProductCategoriesBR(bool preventSecurity)
            {
                this.preventSecurityRestrictions = preventSecurity;
				context = new EFPocoContext();
            }
        #endregion
		
		#region Get

 		public IQueryable<ProductCategory> Get()
        {
            //using (EFContext con = new EFContext())
            //{
				EFContext con = new EFContext();
                var query = con.ProductCategories.AsQueryable();
                con.ContextOptions.ProxyCreationEnabled = false;

                //query = ContextQueryBuilder<Nutrient>.ApplyContextQuery(query, contextRequest);

                return query;




            //}

        }
		
		public List<ProductCategory> GetAll()
        {
            return this.GetBy(p => true);
        }
        public List<ProductCategory> GetAll(string includes)
        {
            return this.GetBy(p => true, includes);
        }
        public ProductCategory GetByKey(Int32 productCategoryID)
        {
            return GetByKey(productCategoryID, true);
        }
        public ProductCategory GetByKey(Int32 productCategoryID, bool loadIncludes)
        {
            ProductCategory item = null;
			var query = PredicateBuilder.True<ProductCategory>();
                    
			string strWhere = "ProductCategoryID = " + productCategoryID.ToString();
            Expression<Func<ProductCategory, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductCategory, bool>(strWhere);
			
			 ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = strWhere;

			//item = GetBy(predicate, loadIncludes, contextRequest).FirstOrDefault();
			item = GetBy(strWhere,loadIncludes,contextRequest).FirstOrDefault();
            return item;
        }
         public List<ProductCategory> GetBy(string strWhere, bool loadRelations, ContextRequest contextRequest)
        {
            if (!loadRelations)
                return GetBy(strWhere, contextRequest);
            else
                return GetBy(strWhere, contextRequest, "");

        }
		  public List<ProductCategory> GetBy(string strWhere, bool loadRelations)
        {
              if (!loadRelations)
                return GetBy(strWhere, new ContextRequest());
            else
                return GetBy(strWhere, new ContextRequest(), "");

        }
         public ProductCategory GetByKey(Int32 productCategoryID, params Expression<Func<ProductCategory, object>>[] includes)
        {
            ProductCategory item = null;
			string strWhere = "ProductCategoryID = " + productCategoryID.ToString();
          Expression<Func<ProductCategory, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductCategory, bool>(strWhere);
			
        item = GetBy(predicate, includes).FirstOrDefault();
         ////   item = GetBy(strWhere,includes).FirstOrDefault();
			return item;

        }
        public ProductCategory GetByKey(Int32 productCategoryID, string includes)
        {
            ProductCategory item = null;
			string strWhere = "ProductCategoryID = " + productCategoryID.ToString();
            
			
            item = GetBy(strWhere, includes).FirstOrDefault();
            return item;

        }

        #region Dynamic Predicate
        public List<ProductCategory> GetBy(Expression<Func<ProductCategory, bool>> predicate, int? pageSize, int? page)
        {
            return this.GetBy(predicate, pageSize, page, null, null);
        }
        public List<ProductCategory> GetBy(Expression<Func<ProductCategory, bool>> predicate, ContextRequest contextRequest)
        {

            return GetBy(predicate, contextRequest,"");
        }
        
        public List<ProductCategory> GetBy(Expression<Func<ProductCategory, bool>> predicate, ContextRequest contextRequest, params Expression<Func<ProductCategory, object>>[] includes)
        {
            StringBuilder sb = new StringBuilder();
           if (includes != null)
            {
                foreach (var path in includes)
                {

						if (sb.Length > 0) sb.Append(",");
						sb.Append(SFSdotNet.Framework.Linq.Utils.IncludeToString<ProductCategory>(path));

               }
            }
            return GetBy(predicate, contextRequest, sb.ToString());
        }
        
        
        public List<ProductCategory> GetBy(Expression<Func<ProductCategory, bool>> predicate, string includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";

            return GetBy(predicate, context, includes);
        }

        public List<ProductCategory> GetBy(Expression<Func<ProductCategory, bool>> predicate, params Expression<Func<ProductCategory, object>>[] includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";
            return GetBy(predicate, context, includes);
        }

      
		public bool DisableCache { get; set; }
		 public List<ProductCategory> GetBy(Expression<Func<ProductCategory, bool>> predicate, ContextRequest contextRequest, string includes)
        {
            using (EFPocoContext con = new EFPocoContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;

				List<ProductCategory> result = null;
                 e = null;
                OnGetting(con,e = new BusinessRulesEventArgs<ProductCategory>() { FilterExpression = predicate, ContextRequest = contextRequest, FilterExpressionString = contextRequest.CustomQuery.FilterExpressionString});
				   if (e != null) {
				    predicate = e.FilterExpression;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				con.EnableChangeTrackingUsingProxies = false;
				con.WrappedContext.ProductCategories.MergeOption = MergeOption.NoTracking;
                con.WrappedContext.ContextOptions.ProxyCreationEnabled = false;
                if (predicate == null) predicate = PredicateBuilder.True<ProductCategory>();
 				string fkIncludes = "ProductCategory2";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.ProductCategories;
				 
                IQueryable<ProductCategory> query = es.AsQueryable();

                                if (!string.IsNullOrEmpty(includes))
                {
                    foreach (string include in includes.Split(char.Parse(",")))
                    {
						if (!string.IsNullOrEmpty(include))
                            query = query.Include(include);
                    }
                }
				query =query.Where(predicate);
                query = ContextQueryBuilder<ProductCategory>.ApplyContextQuery(query, contextRequest);

                result = query.ToList<ProductCategory>();
				e = null;
				OnTaken(this, e = new BusinessRulesEventArgs<ProductCategory>() { Items= result, FilterExpression = predicate });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
        public List<ProductCategory> GetBy(string predicateString, ContextRequest contextRequest, string includes)
        {
            using (EFContext con = new EFContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;


				List<ProductCategory> result = null;
                 e = null;
                  OnGetting(con,e = new BusinessRulesEventArgs<ProductCategory>() {  ContextRequest = contextRequest, FilterExpressionString = predicateString });
			   	if (e != null) {
				    predicateString = e.FilterExpressionString;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				//con.EnableChangeTrackingUsingProxies = false;
				con.ProductCategories.MergeOption = MergeOption.NoTracking;
                con.ContextOptions.ProxyCreationEnabled = false;
                //if (predicate == null) predicate = PredicateBuilder.True<ProductCategory>();
 				string fkIncludes = "ProductCategory2";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}else{
                    contextRequest = new ContextRequest();
                    contextRequest.CustomQuery = new CustomQuery();

                }
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.ProductCategories;
				IQueryable<ProductCategory> query = es.AsQueryable();

		
				// include relations FK
				if(string.IsNullOrEmpty(includes) ){
					includes ="";
				}
				bool includeProductCategory2 = includes.Split(char.Parse(",")).Contains("ProductCategory2");

				
				//string predicateString = predicate.ToDynamicLinq<ProductCategory>();
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicateString, ref predicateWithManyRelations, ref predicateWithFKAndComputed);
                var _queryable = query.AsQueryable();
                if (!string.IsNullOrEmpty(predicateWithManyRelations))
                    _queryable = _queryable.Where(predicateWithManyRelations);
 
				var  queryable = _queryable.Select(                    
				p => 
                        new
                    {
					ProductCategoryID = p.ProductCategoryID
,Name = p.Name
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

,ProductCategory2 = includeProductCategory2 ? p.ProductCategory2:null


	
                    }
                    
                    );
					
				
                    if (!string.IsNullOrEmpty(predicateWithFKAndComputed))
                        queryable = queryable.Where(predicateWithFKAndComputed, contextRequest.CustomQuery.ExtraParams);

				QueryComplementOptions queryOps = ContextQueryBuilder.ApplyContextQuery(contextRequest);
            	if (!string.IsNullOrEmpty(queryOps.OrderByAndSort))
					queryable = queryable.OrderBy(queryOps.OrderByAndSort);
               	if (queryOps.Skip != null)
                {
                    queryable = queryable.Skip(queryOps.Skip.Value);
                }
                if (queryOps.PageSize != null)
                {
                    queryable = queryable.Take (queryOps.PageSize.Value);
                }
                result = queryable.AsEnumerable().
                    Select(
                    p =>  new ProductCategory()
                    {
					ProductCategoryID = p.ProductCategoryID
,Name = p.Name
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate
,ProductCategory2 = p.ProductCategory2

                    }
                     ).ToList();

				e = null;
			OnTaken(this, e = new BusinessRulesEventArgs<ProductCategory>() { Items= result, FilterExpressionString  = predicateString });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
		public List<ProductCategory> GetBy(Expression<Func<ProductCategory, bool>> predicate, bool loadRelations, ContextRequest contextRequest)
        {
			if(!loadRelations)
				return GetBy(predicate, contextRequest);
			else
				return GetBy(predicate, contextRequest, "Products,ProductCategory1");

        }

        public List<ProductCategory> GetBy(Expression<Func<ProductCategory, bool>> predicate, int? pageSize, int? page, string orderBy, SFSdotNet.Framework.Data.SortDirection? sortDirection)
        {
            return GetBy(predicate, new ContextRequest() { CustomQuery = new CustomQuery() { Page = page, PageSize = pageSize, OrderBy = orderBy, SortDirection = sortDirection } });
        }
        public List<ProductCategory> GetBy(Expression<Func<ProductCategory, bool>> predicate)
        {
		
			ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = null;
            return this.GetBy(predicate, contextRequest, "");
        }
        #endregion
        #region Dynamic String
		private string GetSpecificFilter(string filter) {
            string result = "";
		    string linqFilter = String.Empty;
            string freeTextFilter = String.Empty;
            if (filter.Contains("|"))
            {
                linqFilter = filter.Split(char.Parse("|"))[0];
                freeTextFilter = filter.Split(char.Parse("|"))[1];
            }
 			else {
                linqFilter = filter;
            }
            string specificFilter = linqFilter;
            if (!string.IsNullOrEmpty(freeTextFilter))
            {
                System.Text.StringBuilder sbCont = new System.Text.StringBuilder();
                if (specificFilter.Length > 0)
                {
                    sbCont.Append(" AND ");
                    sbCont.Append(" ({0})");
                }
                else
                {
                    sbCont.Append("{0}");
                }
                var words = freeTextFilter.Split(char.Parse(" "));
                System.Text.StringBuilder sbSpec = new System.Text.StringBuilder();
                 int nWords = 1;
				foreach (var word in words)
                {
                    if (sbSpec.Length > 0) sbSpec.Append(" AND ");
                    sbSpec.Append("(");
					
	
					
											
					sbSpec.Append(string.Format(@"Name.Contains(""{0}"")", word));

					
	
					
	
					
	
					
			
                    sbSpec.Append(")");
					
					nWords++;

                }
                specificFilter = string.Format("{0}{1}", specificFilter, string.Format(sbCont.ToString(), sbSpec.ToString()));
            }
			result = specificFilter;
			
			return result;

		}
		public List<ProductCategory> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params object[] extraParams)
        {
        	string specificFilter = "";
            if (!string.IsNullOrEmpty(filter))
              specificFilter=  GetSpecificFilter(filter);
            if (string.IsNullOrEmpty(orderBy))
            {
			                orderBy = "Name";
            }
			SFSdotNet.Framework.Data.SortDirection direction = SFSdotNet.Framework.Data.SortDirection.Ascending;
            if (!string.IsNullOrEmpty(orderDir))
            {
                if (orderDir == "desc")
                    direction = SFSdotNet.Framework.Data.SortDirection.Descending;
            }
            return BR.ProductCategoriesBR.Instance.GetBy(specificFilter,
                new SFSdotNet.Framework.My.ContextRequest()
                {
                    CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
                    {
						ExtraParams= extraParams,
               
                        OrderBy = orderBy,
                        SortDirection = direction,
                        Page = page,
                        PageSize = pageSize
                    }
                });
        }


        public List<ProductCategory> GetBy(string strWhere, ContextRequest contextRequest)
        {
        	#region old code
				Expression<Func<ProductCategory, bool>> predicate = null;
                if (!string.IsNullOrEmpty(strWhere)){

                    object[] extraParams = null;
                    if (contextRequest != null )
                        if (contextRequest.CustomQuery != null )
                            extraParams = contextRequest.CustomQuery.ExtraParams;
                    predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductCategory, bool>(strWhere, extraParams);				}
				 if (contextRequest == null)
                {
                    contextRequest = new ContextRequest();
                    if (contextRequest.CustomQuery == null)
                        contextRequest.CustomQuery = new CustomQuery();
                }
                
            contextRequest.CustomQuery.FilterExpressionString = strWhere;
				//return GetBy(predicate, contextRequest);  

			#endregion				
				
                    return GetBy(strWhere, contextRequest, "");  


        }
       public List<ProductCategory> GetBy(string strWhere)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
			
            return GetBy(strWhere, context, null);
        }

        public List<ProductCategory> GetBy(string strWhere, string includes)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
            return GetBy(strWhere, context, includes);
        }

        #endregion
        #endregion
		
		  #region SaveOrUpdate
        private ProductCategory Save(ProductCategory entity, bool saveChanges, EFPocoContext con)
        {
				ObjectContext context = null;
            return Update(entity, saveChanges, out context);

			
        }

 		 public ProductCategory Create(ProductCategory entity)
        {
				ObjectContext context = null;
				return this.Create(entity, true, out context);

        }
         public ProductCategory Create(ProductCategory entity, bool saveChanges, out ObjectContext context)
        {
                    return Create(entity, saveChanges , out context, null);
        }
         public ProductCategory Create(ProductCategory entity, params Expression<Func<ProductCategory,object>>[] paths)
        {
            ObjectContext context = null;
            if(paths != null)
				return Create(entity, true, out context, paths);
			else 
				return Create(entity, true, out context);
        }
        public ProductCategory Create(ProductCategory entity, bool saveChanges, out ObjectContext context, params Expression<Func<ProductCategory,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				ProductCategory itemResult = null;
#region Autos
	

			entity.rowguid = Guid.NewGuid();
	
	

#endregion
                e = null;
                OnCreating(this,e = new BusinessRulesEventArgs<ProductCategory>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							context = null;
							return e.Item;

						}
					}



				ProductCategoryAdapter adapter = con.GetAdapterObject<ProductCategoryAdapter>(entity);;
				List<Expression<Func<ProductCategoryAdapter, object>>> paths = new List<Expression<Func<ProductCategoryAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(ProductCategoryAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<ProductCategoryAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "Products":
								path = p => p.Products.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.Products.First().ProductModel.WithoutUpdate();											
							break;
                        
							case "ProductCategory1":
								path = p => p.ProductCategory1.First().WithoutUpdate();

								//path = p => member;
							break;
							
							default:
								path = p => member;
							break;
                        }

                        
                       paths.Add(path.Expand());
                    }
                }
                object aux = null;
					paths.Add(p => p.ProductCategory2.WithoutUpdate());

					//paths = pathBuilder.ToArray();

#region Childs Products 
				if (adapter.Products != null)
                {
                    foreach (var item in adapter.Products)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("Products", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.Products.First().WithoutUpdate());
								
							if (item.ProductCategory == null)
								item.ProductCategory = adapter;

						if (item.ProductModel != null){
							item.ProductModel.EntityKey = con.WrappedContext.CreateEntityKey("ProductModels", item.ProductModel);
                            
             
						}								
								item.EntityKey = null;
							}

                    }
					if (adapter.Products.Count > 0){
						paths.Add(p => p.Products.First().WithoutUpdate());
						paths.Add(p => p.Products.First().ProductModel.WithoutUpdate());
					
					}
                }
#endregion 

#region Childs ProductCategory1 
				if (adapter.ProductCategory1 != null)
                {
                    foreach (var item in adapter.ProductCategory1)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("ProductCategories", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.ProductCategory1.First().WithoutUpdate());
								
							if (item.ProductCategory2 == null)
								item.ProductCategory2 = adapter;

								item.EntityKey = null;
							}

                    }
					if (adapter.ProductCategory1.Count > 0){
						paths.Add(p => p.ProductCategory1.First().WithoutUpdate());
											
					}
                }
#endregion 

				if (adapter.ProductCategory2 != null ){
					if(adapter.ProductCategory2.EntityKey == null) adapter.ProductCategory2.EntityKey = con.WrappedContext.CreateEntityKey("ProductCategories", adapter.ProductCategory2);
				}



                //con.WrappedContext.AttachObjectGraph<ProductCategoryAdapter>(adapter, p=>p.Products, p=>p.ProductCategory1, p=>p.ProductCategory2);
                con.WrappedContext.AttachObjectGraph<ProductCategoryAdapter>(adapter, paths.ToArray());
              	if (saveChanges){
                    con.WrappedContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
					 
				}
                else
                    con.WrappedContext.SaveChanges(SaveOptions.None);
                if (!saveChanges)
                    context = con.WrappedContext;
                else
                    context = null;
				itemResult = adapter.PocoEntity;
                OnCreated(this, e = new BusinessRulesEventArgs<ProductCategory>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });
                return itemResult;
            }
        }
        BusinessRulesEventArgs<ProductCategory> e = null;
        public void Create(List<ProductCategory> entities)
        {
				ObjectContext context = null;
				foreach (ProductCategory entity in entities)
				{
					this.Create(entity, true, out context);
				}

				
				
        }

        public ProductCategory Update(ProductCategory entity)
        {
			ObjectContext context = null;
            return Update(entity, true, out context, null);

        }
         public ProductCategory Update(ProductCategory entity, params Expression<Func<ProductCategory, object>>[] paths)
        {
			  ObjectContext context = null;
            return Update(entity, true, out context, paths);
         }
        public ProductCategory Update(ProductCategory entity, bool saveChanges, out ObjectContext outcontext)
        {
			return Update(entity, saveChanges, out outcontext, null);
		}
         public ProductCategory Update(ProductCategory entity, bool saveChanges, out ObjectContext outcontext, params Expression<Func<ProductCategory,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				ProductCategory  itemResult = null;

	

				e = null;
                OnUpdating(this,e = new BusinessRulesEventArgs<ProductCategory>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							outcontext = null;
							return e.Item;

						}
					}

                ProductCategoryAdapter adapter = con.GetAdapterObject<ProductCategoryAdapter>(entity);
                adapter.EntityKey = con.WrappedContext.CreateEntityKey("ProductCategories", adapter);
				    var es = con.ProductCategories;
				List<Expression<Func<ProductCategoryAdapter, object>>> paths = new List<Expression<Func<ProductCategoryAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(ProductCategoryAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<ProductCategoryAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "Products":
								//path = p => member;
								path = p => p.Products.First().WithoutUpdate();
				//				path = p => p.Products.First().ProductModel.WithoutUpdate();											
							break;
                        
							case "ProductCategory1":
								//path = p => member;
								path = p => p.ProductCategory1.First().WithoutUpdate();
							break;
							
							default:
								path = p => member;
							break;
                        }

                        paths.Add(path.Expand());
 					}
                }
                else {
                  paths = new List<Expression<Func<ProductCategoryAdapter, object>>>();

					//List<Expression<Func<ProductCategoryAdapter,object>>> pathBuilder = new List<Expression<Func<ProductCategoryAdapter,object>>>();
					paths.Add(p => p.ProductCategory2.WithoutUpdate());

		
					//paths = pathBuilder.ToArray();		
			}
			object aux = null;
				if (adapter.Products != null)
                {
                    foreach (var item in adapter.Products)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("Products", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }
				if (adapter.ProductCategory1 != null)
                {
                    foreach (var item in adapter.ProductCategory1)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("ProductCategories", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }
				if (adapter.ProductCategory2 != null ){
					if(adapter.ProductCategory2.EntityKey == null) adapter.ProductCategory2.EntityKey = con.WrappedContext.CreateEntityKey("ProductCategories", adapter.ProductCategory2);
				}

                



                //con.AttachObjectGraph<ProductCategory>(adapter, p=>p.Products, p=>p.ProductCategory1, p=>p.ProductCategory2);
                con.WrappedContext.AttachObjectGraph<ProductCategoryAdapter>(adapter, paths.ToArray());
				if (saveChanges){
                	con.WrappedContext.SaveChanges();
					 
					}
                if(!saveChanges)
					outcontext = con.WrappedContext;
				else
					outcontext = null;
				itemResult = adapter.PocoEntity;
				OnUpdated(this, e = new BusinessRulesEventArgs<ProductCategory>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });

              	return itemResult;

			  }
        }
        public ProductCategory Save(ProductCategory entity)
        {
			return Save(entity, true, null);
        }
        public int Save(List<ProductCategory> entities)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
			
            int n = 0;
            foreach (ProductCategory item in entities)
            {
                try
                {
                    this.Save(item, false, con);
                    n++;
                }catch (Exception ex){
                    SFSdotNet.Framework.My.EventLog.Exception(ex);
                }
            }
            con.SaveChanges();
            return n;
            }
        }
        #endregion
        #region Delete
        public void Delete(ProductCategory entity)
        {
				ObjectContext context = null;
				this.Delete(entity, true, out context);
			
        }

        
        public void Delete(ProductCategory entity, bool saveChanges, out  ObjectContext context)
        {
			using (EFPocoContext _con = new EFPocoContext())
			{
				int result = 0;
				
               	BusinessRulesEventArgs<ProductCategory> _e = null;
                OnDeleting(this,_e = new BusinessRulesEventArgs<ProductCategory>() { Item=entity, SaveChanges =saveChanges });
				   if (_e != null) {
						if (_e.Cancel)
						{
							context = null;
							return;

						}
					}


				ProductCategoryAdapter adapter = _con.GetAdapterObject<ProductCategoryAdapter>(entity);
                adapter.EntityKey = _con.WrappedContext.CreateEntityKey("ProductCategories", adapter);
                
	            //adapter = _con.WrappedContext.AttachObjectGraph<ProductCategoryAdapter>(adapter);
				_con.WrappedContext.AttachTo("ProductCategories", adapter);
                
									_con.WrappedContext.DeleteObject(adapter);
                				
				if (!saveChanges)
                    context = _con.WrappedContext;
                else
                    context = null;
				 SaveOptions saveOption = SaveOptions.None;
                if (saveChanges)
                    saveOption = SaveOptions.AcceptAllChangesAfterSave;

				result = _con.WrappedContext.SaveChanges(saveOption);
				if (saveChanges){
					
					}
				if (_e == null)
					_e = new BusinessRulesEventArgs<ProductCategory>() { Item = entity };
                OnDeleted(this, _e );

				//return null;
			}            
        }
        public void Delete(List<ProductCategory> entities)
        {
				ObjectContext context = null;
			
				foreach (ProductCategory item in entities)
				{
					this.Delete(item, true, out context);
				}
			

			
        }
        #endregion
 
        #region GetCount
        public int GetCount(Expression<Func<ProductCategory, bool>> predicate)
        {
		
			using (EFPocoContext con = new EFPocoContext())
			{


				if (predicate == null) predicate = PredicateBuilder.True<ProductCategory>();
				
				return con.ProductCategories.Count(predicate);
			}

        }
        public int GetCount(string predicate)
        {
			e = null;
            OnCounting(this, e = new BusinessRulesEventArgs<ProductCategory>() {  FilterExpressionString = predicate });
            if (e != null)
            {
                if (e.Cancel)
                {
                    context = null;
                    return e.CountResult;

                }
                predicate = e.FilterExpressionString;
            
            }
					predicate = GetSpecificFilter(predicate);
			using (EFContext con = new EFContext())
			{
				   
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicate, ref predicateWithManyRelations, ref predicateWithFKAndComputed);

                if (!string.IsNullOrEmpty(predicate))
                {
				
					
                    return con.ProductCategories.Count(System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductCategory, bool>(predicate));
					
                }else
                    return con.ProductCategories.Count();

			}

		}
         public int GetCount()
        {
            return GetCount(p => true);
        }
        #endregion
        
         public ProductCategory Update(ProductCategory entity, string paths)
        {
            return Update(entity, paths.Split(char.Parse(",")));
            
        }

        public ProductCategory Update(ProductCategory entity, string[] paths)
        {
            // Translate
            List<Expression<Func<ProductCategory, object>>> pathList = new List<Expression<Func<ProductCategory, object>>>();
            for (int i = 0; i <= paths.Length -1; i++)
            {
                var param = Expression.Parameter(typeof(ProductCategory), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<ProductCategory, object>> path = p => member;
                pathList.Add(path.Expand());
            }
           return Update(entity, pathList.ToArray());
        }

        public void Update(List<ProductCategory> entities, string paths)
        {
            foreach (var entity in entities )
            {
                Update(entity, paths);
            }
        }

        public ProductCategory Create(ProductCategory entity, string paths)
        {
			if(string.IsNullOrEmpty(paths))
				return Create(entity);
				
            return Create(entity, paths.Split(char.Parse(",")));
        }

        public  void Create(List<ProductCategory> entities, string paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }

        public void Create(List<ProductCategory> entities, string[] paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }
        
        public ProductCategory  Create(ProductCategory entity, string[] paths)
        {
            List<Expression<Func<ProductCategory, object>>> pathList = new List<Expression<Func<ProductCategory, object>>>();
            for (int i = 0; i < paths.Length - 1; i++)
            {
                var param = Expression.Parameter(typeof(ProductCategory), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<ProductCategory, object>> path = p => member;
                pathList.Add(path.Expand());
            }
            return Create(entity, pathList.ToArray());
        }
        public void Delete(List<ProductCategory.CompositeKey> entityKeys)
        {

            List<ProductCategory> items = new List<ProductCategory>();
            foreach (var itemKey in entityKeys)
            {
                items.Add(GetByKey(itemKey.ProductCategoryID));
            }

            Delete(items);

        }
		
		
	}
		public partial class ProductDescriptionsBR{
	 	
           
		 #region Partial methods

           partial void OnUpdating(object sender, BusinessRulesEventArgs<ProductDescription> e);

            partial void OnUpdated(object sender, BusinessRulesEventArgs<ProductDescription> e);

            partial void OnCreating(object sender, BusinessRulesEventArgs<ProductDescription> e);
            partial void OnCreated(object sender, BusinessRulesEventArgs<ProductDescription> e);

            partial void OnDeleting(object sender, BusinessRulesEventArgs<ProductDescription> e);
            partial void OnDeleted(object sender, BusinessRulesEventArgs<ProductDescription> e);

            partial void OnGetting(object sender, BusinessRulesEventArgs<ProductDescription> e);
            partial void OnTaken(object sender, BusinessRulesEventArgs<ProductDescription> e);
            partial void OnCounting(object sender, BusinessRulesEventArgs<ProductDescription> e);
 
 
            #endregion
			
		private static ProductDescriptionsBR singlenton =null;
				public static ProductDescriptionsBR NewInstance(){
					return  new ProductDescriptionsBR();
					
				}
		public static ProductDescriptionsBR Instance{
			get{
				if (singlenton == null)
					singlenton = new ProductDescriptionsBR();
				return singlenton;
			}
		}
		private bool preventSecurityRestrictions = false;

		#region Fields
        EFPocoContext context = null;
        #endregion
        #region Constructor
        public ProductDescriptionsBR()
        {
            context = new EFPocoContext();
        }
		 public ProductDescriptionsBR(bool preventSecurity)
            {
                this.preventSecurityRestrictions = preventSecurity;
				context = new EFPocoContext();
            }
        #endregion
		
		#region Get

 		public IQueryable<ProductDescription> Get()
        {
            //using (EFContext con = new EFContext())
            //{
				EFContext con = new EFContext();
                var query = con.ProductDescriptions.AsQueryable();
                con.ContextOptions.ProxyCreationEnabled = false;

                //query = ContextQueryBuilder<Nutrient>.ApplyContextQuery(query, contextRequest);

                return query;




            //}

        }
		
		public List<ProductDescription> GetAll()
        {
            return this.GetBy(p => true);
        }
        public List<ProductDescription> GetAll(string includes)
        {
            return this.GetBy(p => true, includes);
        }
        public ProductDescription GetByKey(Int32 productDescriptionID)
        {
            return GetByKey(productDescriptionID, true);
        }
        public ProductDescription GetByKey(Int32 productDescriptionID, bool loadIncludes)
        {
            ProductDescription item = null;
			var query = PredicateBuilder.True<ProductDescription>();
                    
			string strWhere = "ProductDescriptionID = " + productDescriptionID.ToString();
            Expression<Func<ProductDescription, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductDescription, bool>(strWhere);
			
			 ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = strWhere;

			//item = GetBy(predicate, loadIncludes, contextRequest).FirstOrDefault();
			item = GetBy(strWhere,loadIncludes,contextRequest).FirstOrDefault();
            return item;
        }
         public List<ProductDescription> GetBy(string strWhere, bool loadRelations, ContextRequest contextRequest)
        {
            if (!loadRelations)
                return GetBy(strWhere, contextRequest);
            else
                return GetBy(strWhere, contextRequest, "");

        }
		  public List<ProductDescription> GetBy(string strWhere, bool loadRelations)
        {
              if (!loadRelations)
                return GetBy(strWhere, new ContextRequest());
            else
                return GetBy(strWhere, new ContextRequest(), "");

        }
         public ProductDescription GetByKey(Int32 productDescriptionID, params Expression<Func<ProductDescription, object>>[] includes)
        {
            ProductDescription item = null;
			string strWhere = "ProductDescriptionID = " + productDescriptionID.ToString();
          Expression<Func<ProductDescription, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductDescription, bool>(strWhere);
			
        item = GetBy(predicate, includes).FirstOrDefault();
         ////   item = GetBy(strWhere,includes).FirstOrDefault();
			return item;

        }
        public ProductDescription GetByKey(Int32 productDescriptionID, string includes)
        {
            ProductDescription item = null;
			string strWhere = "ProductDescriptionID = " + productDescriptionID.ToString();
            
			
            item = GetBy(strWhere, includes).FirstOrDefault();
            return item;

        }

        #region Dynamic Predicate
        public List<ProductDescription> GetBy(Expression<Func<ProductDescription, bool>> predicate, int? pageSize, int? page)
        {
            return this.GetBy(predicate, pageSize, page, null, null);
        }
        public List<ProductDescription> GetBy(Expression<Func<ProductDescription, bool>> predicate, ContextRequest contextRequest)
        {

            return GetBy(predicate, contextRequest,"");
        }
        
        public List<ProductDescription> GetBy(Expression<Func<ProductDescription, bool>> predicate, ContextRequest contextRequest, params Expression<Func<ProductDescription, object>>[] includes)
        {
            StringBuilder sb = new StringBuilder();
           if (includes != null)
            {
                foreach (var path in includes)
                {

						if (sb.Length > 0) sb.Append(",");
						sb.Append(SFSdotNet.Framework.Linq.Utils.IncludeToString<ProductDescription>(path));

               }
            }
            return GetBy(predicate, contextRequest, sb.ToString());
        }
        
        
        public List<ProductDescription> GetBy(Expression<Func<ProductDescription, bool>> predicate, string includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";

            return GetBy(predicate, context, includes);
        }

        public List<ProductDescription> GetBy(Expression<Func<ProductDescription, bool>> predicate, params Expression<Func<ProductDescription, object>>[] includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";
            return GetBy(predicate, context, includes);
        }

      
		public bool DisableCache { get; set; }
		 public List<ProductDescription> GetBy(Expression<Func<ProductDescription, bool>> predicate, ContextRequest contextRequest, string includes)
        {
            using (EFPocoContext con = new EFPocoContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;

				List<ProductDescription> result = null;
                 e = null;
                OnGetting(con,e = new BusinessRulesEventArgs<ProductDescription>() { FilterExpression = predicate, ContextRequest = contextRequest, FilterExpressionString = contextRequest.CustomQuery.FilterExpressionString});
				   if (e != null) {
				    predicate = e.FilterExpression;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				con.EnableChangeTrackingUsingProxies = false;
				con.WrappedContext.ProductDescriptions.MergeOption = MergeOption.NoTracking;
                con.WrappedContext.ContextOptions.ProxyCreationEnabled = false;
                if (predicate == null) predicate = PredicateBuilder.True<ProductDescription>();
                
                var es = con.ProductDescriptions;
				 
                IQueryable<ProductDescription> query = es.AsQueryable();

                                if (!string.IsNullOrEmpty(includes))
                {
                    foreach (string include in includes.Split(char.Parse(",")))
                    {
						if (!string.IsNullOrEmpty(include))
                            query = query.Include(include);
                    }
                }
				query =query.Where(predicate);
                query = ContextQueryBuilder<ProductDescription>.ApplyContextQuery(query, contextRequest);

                result = query.ToList<ProductDescription>();
				e = null;
				OnTaken(this, e = new BusinessRulesEventArgs<ProductDescription>() { Items= result, FilterExpression = predicate });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
        public List<ProductDescription> GetBy(string predicateString, ContextRequest contextRequest, string includes)
        {
            using (EFContext con = new EFContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;


				List<ProductDescription> result = null;
                 e = null;
                  OnGetting(con,e = new BusinessRulesEventArgs<ProductDescription>() {  ContextRequest = contextRequest, FilterExpressionString = predicateString });
			   	if (e != null) {
				    predicateString = e.FilterExpressionString;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				//con.EnableChangeTrackingUsingProxies = false;
				con.ProductDescriptions.MergeOption = MergeOption.NoTracking;
                con.ContextOptions.ProxyCreationEnabled = false;
                //if (predicate == null) predicate = PredicateBuilder.True<ProductDescription>();
                
                var es = con.ProductDescriptions;
				IQueryable<ProductDescription> query = es.AsQueryable();

		
				// include relations FK
				if(string.IsNullOrEmpty(includes) ){
					includes ="";
				}
				
				//string predicateString = predicate.ToDynamicLinq<ProductDescription>();
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicateString, ref predicateWithManyRelations, ref predicateWithFKAndComputed);
                var _queryable = query.AsQueryable();
                if (!string.IsNullOrEmpty(predicateWithManyRelations))
                    _queryable = _queryable.Where(predicateWithManyRelations);
 
				var  queryable = _queryable.Select(                    
				p => 
                        new
                    {
					ProductDescriptionID = p.ProductDescriptionID
,Description = p.Description
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

,

	
                    }
                    
                    );
					
				
                    if (!string.IsNullOrEmpty(predicateWithFKAndComputed))
                        queryable = queryable.Where(predicateWithFKAndComputed, contextRequest.CustomQuery.ExtraParams);

				QueryComplementOptions queryOps = ContextQueryBuilder.ApplyContextQuery(contextRequest);
            	if (!string.IsNullOrEmpty(queryOps.OrderByAndSort))
					queryable = queryable.OrderBy(queryOps.OrderByAndSort);
               	if (queryOps.Skip != null)
                {
                    queryable = queryable.Skip(queryOps.Skip.Value);
                }
                if (queryOps.PageSize != null)
                {
                    queryable = queryable.Take (queryOps.PageSize.Value);
                }
                result = queryable.AsEnumerable().
                    Select(
                    p =>  new ProductDescription()
                    {
					ProductDescriptionID = p.ProductDescriptionID
,Description = p.Description
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

                    }
                     ).ToList();

				e = null;
			OnTaken(this, e = new BusinessRulesEventArgs<ProductDescription>() { Items= result, FilterExpressionString  = predicateString });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
		public List<ProductDescription> GetBy(Expression<Func<ProductDescription, bool>> predicate, bool loadRelations, ContextRequest contextRequest)
        {
			if(!loadRelations)
				return GetBy(predicate, contextRequest);
			else
				return GetBy(predicate, contextRequest, "ProductModelProductDescriptions");

        }

        public List<ProductDescription> GetBy(Expression<Func<ProductDescription, bool>> predicate, int? pageSize, int? page, string orderBy, SFSdotNet.Framework.Data.SortDirection? sortDirection)
        {
            return GetBy(predicate, new ContextRequest() { CustomQuery = new CustomQuery() { Page = page, PageSize = pageSize, OrderBy = orderBy, SortDirection = sortDirection } });
        }
        public List<ProductDescription> GetBy(Expression<Func<ProductDescription, bool>> predicate)
        {
		
			ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = null;
            return this.GetBy(predicate, contextRequest, "");
        }
        #endregion
        #region Dynamic String
		private string GetSpecificFilter(string filter) {
            string result = "";
		    string linqFilter = String.Empty;
            string freeTextFilter = String.Empty;
            if (filter.Contains("|"))
            {
                linqFilter = filter.Split(char.Parse("|"))[0];
                freeTextFilter = filter.Split(char.Parse("|"))[1];
            }
 			else {
                linqFilter = filter;
            }
            string specificFilter = linqFilter;
            if (!string.IsNullOrEmpty(freeTextFilter))
            {
                System.Text.StringBuilder sbCont = new System.Text.StringBuilder();
                if (specificFilter.Length > 0)
                {
                    sbCont.Append(" AND ");
                    sbCont.Append(" ({0})");
                }
                else
                {
                    sbCont.Append("{0}");
                }
                var words = freeTextFilter.Split(char.Parse(" "));
                System.Text.StringBuilder sbSpec = new System.Text.StringBuilder();
                 int nWords = 1;
				foreach (var word in words)
                {
                    if (sbSpec.Length > 0) sbSpec.Append(" AND ");
                    sbSpec.Append("(");
					
	
					
											
					sbSpec.Append(string.Format(@"Description.Contains(""{0}"")", word));

					
	
					
	
					
			
                    sbSpec.Append(")");
					
					nWords++;

                }
                specificFilter = string.Format("{0}{1}", specificFilter, string.Format(sbCont.ToString(), sbSpec.ToString()));
            }
			result = specificFilter;
			
			return result;

		}
		public List<ProductDescription> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params object[] extraParams)
        {
        	string specificFilter = "";
            if (!string.IsNullOrEmpty(filter))
              specificFilter=  GetSpecificFilter(filter);
            if (string.IsNullOrEmpty(orderBy))
            {
			                orderBy = "Description";
            }
			SFSdotNet.Framework.Data.SortDirection direction = SFSdotNet.Framework.Data.SortDirection.Ascending;
            if (!string.IsNullOrEmpty(orderDir))
            {
                if (orderDir == "desc")
                    direction = SFSdotNet.Framework.Data.SortDirection.Descending;
            }
            return BR.ProductDescriptionsBR.Instance.GetBy(specificFilter,
                new SFSdotNet.Framework.My.ContextRequest()
                {
                    CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
                    {
						ExtraParams= extraParams,
               
                        OrderBy = orderBy,
                        SortDirection = direction,
                        Page = page,
                        PageSize = pageSize
                    }
                });
        }


        public List<ProductDescription> GetBy(string strWhere, ContextRequest contextRequest)
        {
        	#region old code
				Expression<Func<ProductDescription, bool>> predicate = null;
                if (!string.IsNullOrEmpty(strWhere)){

                    object[] extraParams = null;
                    if (contextRequest != null )
                        if (contextRequest.CustomQuery != null )
                            extraParams = contextRequest.CustomQuery.ExtraParams;
                    predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductDescription, bool>(strWhere, extraParams);				}
				 if (contextRequest == null)
                {
                    contextRequest = new ContextRequest();
                    if (contextRequest.CustomQuery == null)
                        contextRequest.CustomQuery = new CustomQuery();
                }
                
            contextRequest.CustomQuery.FilterExpressionString = strWhere;
				//return GetBy(predicate, contextRequest);  

			#endregion				
				
                    return GetBy(strWhere, contextRequest, "");  


        }
       public List<ProductDescription> GetBy(string strWhere)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
			
            return GetBy(strWhere, context, null);
        }

        public List<ProductDescription> GetBy(string strWhere, string includes)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
            return GetBy(strWhere, context, includes);
        }

        #endregion
        #endregion
		
		  #region SaveOrUpdate
        private ProductDescription Save(ProductDescription entity, bool saveChanges, EFPocoContext con)
        {
				ObjectContext context = null;
            return Update(entity, saveChanges, out context);

			
        }

 		 public ProductDescription Create(ProductDescription entity)
        {
				ObjectContext context = null;
				return this.Create(entity, true, out context);

        }
         public ProductDescription Create(ProductDescription entity, bool saveChanges, out ObjectContext context)
        {
                    return Create(entity, saveChanges , out context, null);
        }
         public ProductDescription Create(ProductDescription entity, params Expression<Func<ProductDescription,object>>[] paths)
        {
            ObjectContext context = null;
            if(paths != null)
				return Create(entity, true, out context, paths);
			else 
				return Create(entity, true, out context);
        }
        public ProductDescription Create(ProductDescription entity, bool saveChanges, out ObjectContext context, params Expression<Func<ProductDescription,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				ProductDescription itemResult = null;
#region Autos
	

			entity.rowguid = Guid.NewGuid();
	
	

#endregion
                e = null;
                OnCreating(this,e = new BusinessRulesEventArgs<ProductDescription>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							context = null;
							return e.Item;

						}
					}



				ProductDescriptionAdapter adapter = con.GetAdapterObject<ProductDescriptionAdapter>(entity);;
				List<Expression<Func<ProductDescriptionAdapter, object>>> paths = new List<Expression<Func<ProductDescriptionAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(ProductDescriptionAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<ProductDescriptionAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "ProductModelProductDescriptions":
								path = p => p.ProductModelProductDescriptions.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.ProductModelProductDescriptions.First().ProductModel.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        
                       paths.Add(path.Expand());
                    }
                }
                object aux = null;
					//paths = pathBuilder.ToArray();

#region Childs ProductModelProductDescriptions 
				if (adapter.ProductModelProductDescriptions != null)
                {
                    foreach (var item in adapter.ProductModelProductDescriptions)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("ProductModelProductDescriptions", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.ProductModelProductDescriptions.First().WithoutUpdate());
								
							if (item.ProductDescription == null)
								item.ProductDescription = adapter;

						if (item.ProductModel != null){
							item.ProductModel.EntityKey = con.WrappedContext.CreateEntityKey("ProductModels", item.ProductModel);
                            
             
						}								
								item.EntityKey = null;
							}

                    }
					if (adapter.ProductModelProductDescriptions.Count > 0){
						paths.Add(p => p.ProductModelProductDescriptions.First().WithoutUpdate());
						paths.Add(p => p.ProductModelProductDescriptions.First().ProductModel.WithoutUpdate());
					
					}
                }
#endregion 




                //con.WrappedContext.AttachObjectGraph<ProductDescriptionAdapter>(adapter, p=>p.ProductModelProductDescriptions);
                con.WrappedContext.AttachObjectGraph<ProductDescriptionAdapter>(adapter, paths.ToArray());
              	if (saveChanges){
                    con.WrappedContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
					 
				}
                else
                    con.WrappedContext.SaveChanges(SaveOptions.None);
                if (!saveChanges)
                    context = con.WrappedContext;
                else
                    context = null;
				itemResult = adapter.PocoEntity;
                OnCreated(this, e = new BusinessRulesEventArgs<ProductDescription>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });
                return itemResult;
            }
        }
        BusinessRulesEventArgs<ProductDescription> e = null;
        public void Create(List<ProductDescription> entities)
        {
				ObjectContext context = null;
				foreach (ProductDescription entity in entities)
				{
					this.Create(entity, true, out context);
				}

				
				
        }

        public ProductDescription Update(ProductDescription entity)
        {
			ObjectContext context = null;
            return Update(entity, true, out context, null);

        }
         public ProductDescription Update(ProductDescription entity, params Expression<Func<ProductDescription, object>>[] paths)
        {
			  ObjectContext context = null;
            return Update(entity, true, out context, paths);
         }
        public ProductDescription Update(ProductDescription entity, bool saveChanges, out ObjectContext outcontext)
        {
			return Update(entity, saveChanges, out outcontext, null);
		}
         public ProductDescription Update(ProductDescription entity, bool saveChanges, out ObjectContext outcontext, params Expression<Func<ProductDescription,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				ProductDescription  itemResult = null;

	

				e = null;
                OnUpdating(this,e = new BusinessRulesEventArgs<ProductDescription>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							outcontext = null;
							return e.Item;

						}
					}

                ProductDescriptionAdapter adapter = con.GetAdapterObject<ProductDescriptionAdapter>(entity);
                adapter.EntityKey = con.WrappedContext.CreateEntityKey("ProductDescriptions", adapter);
				    var es = con.ProductDescriptions;
				List<Expression<Func<ProductDescriptionAdapter, object>>> paths = new List<Expression<Func<ProductDescriptionAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(ProductDescriptionAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<ProductDescriptionAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "ProductModelProductDescriptions":
								//path = p => member;
								path = p => p.ProductModelProductDescriptions.First().WithoutUpdate();
				//				path = p => p.ProductModelProductDescriptions.First().ProductModel.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        paths.Add(path.Expand());
 					}
                }
                else {
                  paths = new List<Expression<Func<ProductDescriptionAdapter, object>>>();

					//List<Expression<Func<ProductDescriptionAdapter,object>>> pathBuilder = new List<Expression<Func<ProductDescriptionAdapter,object>>>();
		
					//paths = pathBuilder.ToArray();		
			}
			object aux = null;
				if (adapter.ProductModelProductDescriptions != null)
                {
                    foreach (var item in adapter.ProductModelProductDescriptions)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("ProductModelProductDescriptions", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }



                //con.AttachObjectGraph<ProductDescription>(adapter, p=>p.ProductModelProductDescriptions);
                con.WrappedContext.AttachObjectGraph<ProductDescriptionAdapter>(adapter, paths.ToArray());
				if (saveChanges){
                	con.WrappedContext.SaveChanges();
					 
					}
                if(!saveChanges)
					outcontext = con.WrappedContext;
				else
					outcontext = null;
				itemResult = adapter.PocoEntity;
				OnUpdated(this, e = new BusinessRulesEventArgs<ProductDescription>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });

              	return itemResult;

			  }
        }
        public ProductDescription Save(ProductDescription entity)
        {
			return Save(entity, true, null);
        }
        public int Save(List<ProductDescription> entities)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
			
            int n = 0;
            foreach (ProductDescription item in entities)
            {
                try
                {
                    this.Save(item, false, con);
                    n++;
                }catch (Exception ex){
                    SFSdotNet.Framework.My.EventLog.Exception(ex);
                }
            }
            con.SaveChanges();
            return n;
            }
        }
        #endregion
        #region Delete
        public void Delete(ProductDescription entity)
        {
				ObjectContext context = null;
				this.Delete(entity, true, out context);
			
        }

        
        public void Delete(ProductDescription entity, bool saveChanges, out  ObjectContext context)
        {
			using (EFPocoContext _con = new EFPocoContext())
			{
				int result = 0;
				
               	BusinessRulesEventArgs<ProductDescription> _e = null;
                OnDeleting(this,_e = new BusinessRulesEventArgs<ProductDescription>() { Item=entity, SaveChanges =saveChanges });
				   if (_e != null) {
						if (_e.Cancel)
						{
							context = null;
							return;

						}
					}


				ProductDescriptionAdapter adapter = _con.GetAdapterObject<ProductDescriptionAdapter>(entity);
                adapter.EntityKey = _con.WrappedContext.CreateEntityKey("ProductDescriptions", adapter);
                
	            //adapter = _con.WrappedContext.AttachObjectGraph<ProductDescriptionAdapter>(adapter);
				_con.WrappedContext.AttachTo("ProductDescriptions", adapter);
                
									_con.WrappedContext.DeleteObject(adapter);
                				
				if (!saveChanges)
                    context = _con.WrappedContext;
                else
                    context = null;
				 SaveOptions saveOption = SaveOptions.None;
                if (saveChanges)
                    saveOption = SaveOptions.AcceptAllChangesAfterSave;

				result = _con.WrappedContext.SaveChanges(saveOption);
				if (saveChanges){
					
					}
				if (_e == null)
					_e = new BusinessRulesEventArgs<ProductDescription>() { Item = entity };
                OnDeleted(this, _e );

				//return null;
			}            
        }
        public void Delete(List<ProductDescription> entities)
        {
				ObjectContext context = null;
			
				foreach (ProductDescription item in entities)
				{
					this.Delete(item, true, out context);
				}
			

			
        }
        #endregion
 
        #region GetCount
        public int GetCount(Expression<Func<ProductDescription, bool>> predicate)
        {
		
			using (EFPocoContext con = new EFPocoContext())
			{


				if (predicate == null) predicate = PredicateBuilder.True<ProductDescription>();
				
				return con.ProductDescriptions.Count(predicate);
			}

        }
        public int GetCount(string predicate)
        {
			e = null;
            OnCounting(this, e = new BusinessRulesEventArgs<ProductDescription>() {  FilterExpressionString = predicate });
            if (e != null)
            {
                if (e.Cancel)
                {
                    context = null;
                    return e.CountResult;

                }
                predicate = e.FilterExpressionString;
            
            }
					predicate = GetSpecificFilter(predicate);
			using (EFContext con = new EFContext())
			{
				   
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicate, ref predicateWithManyRelations, ref predicateWithFKAndComputed);

                if (!string.IsNullOrEmpty(predicate))
                {
				
					
                    return con.ProductDescriptions.Count(System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductDescription, bool>(predicate));
					
                }else
                    return con.ProductDescriptions.Count();

			}

		}
         public int GetCount()
        {
            return GetCount(p => true);
        }
        #endregion
        
         public ProductDescription Update(ProductDescription entity, string paths)
        {
            return Update(entity, paths.Split(char.Parse(",")));
            
        }

        public ProductDescription Update(ProductDescription entity, string[] paths)
        {
            // Translate
            List<Expression<Func<ProductDescription, object>>> pathList = new List<Expression<Func<ProductDescription, object>>>();
            for (int i = 0; i <= paths.Length -1; i++)
            {
                var param = Expression.Parameter(typeof(ProductDescription), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<ProductDescription, object>> path = p => member;
                pathList.Add(path.Expand());
            }
           return Update(entity, pathList.ToArray());
        }

        public void Update(List<ProductDescription> entities, string paths)
        {
            foreach (var entity in entities )
            {
                Update(entity, paths);
            }
        }

        public ProductDescription Create(ProductDescription entity, string paths)
        {
			if(string.IsNullOrEmpty(paths))
				return Create(entity);
				
            return Create(entity, paths.Split(char.Parse(",")));
        }

        public  void Create(List<ProductDescription> entities, string paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }

        public void Create(List<ProductDescription> entities, string[] paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }
        
        public ProductDescription  Create(ProductDescription entity, string[] paths)
        {
            List<Expression<Func<ProductDescription, object>>> pathList = new List<Expression<Func<ProductDescription, object>>>();
            for (int i = 0; i < paths.Length - 1; i++)
            {
                var param = Expression.Parameter(typeof(ProductDescription), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<ProductDescription, object>> path = p => member;
                pathList.Add(path.Expand());
            }
            return Create(entity, pathList.ToArray());
        }
        public void Delete(List<ProductDescription.CompositeKey> entityKeys)
        {

            List<ProductDescription> items = new List<ProductDescription>();
            foreach (var itemKey in entityKeys)
            {
                items.Add(GetByKey(itemKey.ProductDescriptionID));
            }

            Delete(items);

        }
		
		
	}
		public partial class ProductModelsBR{
	 	
           
		 #region Partial methods

           partial void OnUpdating(object sender, BusinessRulesEventArgs<ProductModel> e);

            partial void OnUpdated(object sender, BusinessRulesEventArgs<ProductModel> e);

            partial void OnCreating(object sender, BusinessRulesEventArgs<ProductModel> e);
            partial void OnCreated(object sender, BusinessRulesEventArgs<ProductModel> e);

            partial void OnDeleting(object sender, BusinessRulesEventArgs<ProductModel> e);
            partial void OnDeleted(object sender, BusinessRulesEventArgs<ProductModel> e);

            partial void OnGetting(object sender, BusinessRulesEventArgs<ProductModel> e);
            partial void OnTaken(object sender, BusinessRulesEventArgs<ProductModel> e);
            partial void OnCounting(object sender, BusinessRulesEventArgs<ProductModel> e);
 
 
            #endregion
			
		private static ProductModelsBR singlenton =null;
				public static ProductModelsBR NewInstance(){
					return  new ProductModelsBR();
					
				}
		public static ProductModelsBR Instance{
			get{
				if (singlenton == null)
					singlenton = new ProductModelsBR();
				return singlenton;
			}
		}
		private bool preventSecurityRestrictions = false;

		#region Fields
        EFPocoContext context = null;
        #endregion
        #region Constructor
        public ProductModelsBR()
        {
            context = new EFPocoContext();
        }
		 public ProductModelsBR(bool preventSecurity)
            {
                this.preventSecurityRestrictions = preventSecurity;
				context = new EFPocoContext();
            }
        #endregion
		
		#region Get

 		public IQueryable<ProductModel> Get()
        {
            //using (EFContext con = new EFContext())
            //{
				EFContext con = new EFContext();
                var query = con.ProductModels.AsQueryable();
                con.ContextOptions.ProxyCreationEnabled = false;

                //query = ContextQueryBuilder<Nutrient>.ApplyContextQuery(query, contextRequest);

                return query;




            //}

        }
		
		public List<ProductModel> GetAll()
        {
            return this.GetBy(p => true);
        }
        public List<ProductModel> GetAll(string includes)
        {
            return this.GetBy(p => true, includes);
        }
        public ProductModel GetByKey(Int32 productModelID)
        {
            return GetByKey(productModelID, true);
        }
        public ProductModel GetByKey(Int32 productModelID, bool loadIncludes)
        {
            ProductModel item = null;
			var query = PredicateBuilder.True<ProductModel>();
                    
			string strWhere = "ProductModelID = " + productModelID.ToString();
            Expression<Func<ProductModel, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductModel, bool>(strWhere);
			
			 ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = strWhere;

			//item = GetBy(predicate, loadIncludes, contextRequest).FirstOrDefault();
			item = GetBy(strWhere,loadIncludes,contextRequest).FirstOrDefault();
            return item;
        }
         public List<ProductModel> GetBy(string strWhere, bool loadRelations, ContextRequest contextRequest)
        {
            if (!loadRelations)
                return GetBy(strWhere, contextRequest);
            else
                return GetBy(strWhere, contextRequest, "");

        }
		  public List<ProductModel> GetBy(string strWhere, bool loadRelations)
        {
              if (!loadRelations)
                return GetBy(strWhere, new ContextRequest());
            else
                return GetBy(strWhere, new ContextRequest(), "");

        }
         public ProductModel GetByKey(Int32 productModelID, params Expression<Func<ProductModel, object>>[] includes)
        {
            ProductModel item = null;
			string strWhere = "ProductModelID = " + productModelID.ToString();
          Expression<Func<ProductModel, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductModel, bool>(strWhere);
			
        item = GetBy(predicate, includes).FirstOrDefault();
         ////   item = GetBy(strWhere,includes).FirstOrDefault();
			return item;

        }
        public ProductModel GetByKey(Int32 productModelID, string includes)
        {
            ProductModel item = null;
			string strWhere = "ProductModelID = " + productModelID.ToString();
            
			
            item = GetBy(strWhere, includes).FirstOrDefault();
            return item;

        }

        #region Dynamic Predicate
        public List<ProductModel> GetBy(Expression<Func<ProductModel, bool>> predicate, int? pageSize, int? page)
        {
            return this.GetBy(predicate, pageSize, page, null, null);
        }
        public List<ProductModel> GetBy(Expression<Func<ProductModel, bool>> predicate, ContextRequest contextRequest)
        {

            return GetBy(predicate, contextRequest,"");
        }
        
        public List<ProductModel> GetBy(Expression<Func<ProductModel, bool>> predicate, ContextRequest contextRequest, params Expression<Func<ProductModel, object>>[] includes)
        {
            StringBuilder sb = new StringBuilder();
           if (includes != null)
            {
                foreach (var path in includes)
                {

						if (sb.Length > 0) sb.Append(",");
						sb.Append(SFSdotNet.Framework.Linq.Utils.IncludeToString<ProductModel>(path));

               }
            }
            return GetBy(predicate, contextRequest, sb.ToString());
        }
        
        
        public List<ProductModel> GetBy(Expression<Func<ProductModel, bool>> predicate, string includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";

            return GetBy(predicate, context, includes);
        }

        public List<ProductModel> GetBy(Expression<Func<ProductModel, bool>> predicate, params Expression<Func<ProductModel, object>>[] includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";
            return GetBy(predicate, context, includes);
        }

      
		public bool DisableCache { get; set; }
		 public List<ProductModel> GetBy(Expression<Func<ProductModel, bool>> predicate, ContextRequest contextRequest, string includes)
        {
            using (EFPocoContext con = new EFPocoContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;

				List<ProductModel> result = null;
                 e = null;
                OnGetting(con,e = new BusinessRulesEventArgs<ProductModel>() { FilterExpression = predicate, ContextRequest = contextRequest, FilterExpressionString = contextRequest.CustomQuery.FilterExpressionString});
				   if (e != null) {
				    predicate = e.FilterExpression;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				con.EnableChangeTrackingUsingProxies = false;
				con.WrappedContext.ProductModels.MergeOption = MergeOption.NoTracking;
                con.WrappedContext.ContextOptions.ProxyCreationEnabled = false;
                if (predicate == null) predicate = PredicateBuilder.True<ProductModel>();
                
                var es = con.ProductModels;
				 
                IQueryable<ProductModel> query = es.AsQueryable();

                                if (!string.IsNullOrEmpty(includes))
                {
                    foreach (string include in includes.Split(char.Parse(",")))
                    {
						if (!string.IsNullOrEmpty(include))
                            query = query.Include(include);
                    }
                }
				query =query.Where(predicate);
                query = ContextQueryBuilder<ProductModel>.ApplyContextQuery(query, contextRequest);

                result = query.ToList<ProductModel>();
				e = null;
				OnTaken(this, e = new BusinessRulesEventArgs<ProductModel>() { Items= result, FilterExpression = predicate });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
        public List<ProductModel> GetBy(string predicateString, ContextRequest contextRequest, string includes)
        {
            using (EFContext con = new EFContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;


				List<ProductModel> result = null;
                 e = null;
                  OnGetting(con,e = new BusinessRulesEventArgs<ProductModel>() {  ContextRequest = contextRequest, FilterExpressionString = predicateString });
			   	if (e != null) {
				    predicateString = e.FilterExpressionString;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				//con.EnableChangeTrackingUsingProxies = false;
				con.ProductModels.MergeOption = MergeOption.NoTracking;
                con.ContextOptions.ProxyCreationEnabled = false;
                //if (predicate == null) predicate = PredicateBuilder.True<ProductModel>();
                
                var es = con.ProductModels;
				IQueryable<ProductModel> query = es.AsQueryable();

		
				// include relations FK
				if(string.IsNullOrEmpty(includes) ){
					includes ="";
				}
				
				//string predicateString = predicate.ToDynamicLinq<ProductModel>();
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicateString, ref predicateWithManyRelations, ref predicateWithFKAndComputed);
                var _queryable = query.AsQueryable();
                if (!string.IsNullOrEmpty(predicateWithManyRelations))
                    _queryable = _queryable.Where(predicateWithManyRelations);
 
				var  queryable = _queryable.Select(                    
				p => 
                        new
                    {
					ProductModelID = p.ProductModelID
,Name = p.Name
,CatalogDescription = p.CatalogDescription
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

,

	
                    }
                    
                    );
					
				
                    if (!string.IsNullOrEmpty(predicateWithFKAndComputed))
                        queryable = queryable.Where(predicateWithFKAndComputed, contextRequest.CustomQuery.ExtraParams);

				QueryComplementOptions queryOps = ContextQueryBuilder.ApplyContextQuery(contextRequest);
            	if (!string.IsNullOrEmpty(queryOps.OrderByAndSort))
					queryable = queryable.OrderBy(queryOps.OrderByAndSort);
               	if (queryOps.Skip != null)
                {
                    queryable = queryable.Skip(queryOps.Skip.Value);
                }
                if (queryOps.PageSize != null)
                {
                    queryable = queryable.Take (queryOps.PageSize.Value);
                }
                result = queryable.AsEnumerable().
                    Select(
                    p =>  new ProductModel()
                    {
					ProductModelID = p.ProductModelID
,Name = p.Name
,CatalogDescription = p.CatalogDescription
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

                    }
                     ).ToList();

				e = null;
			OnTaken(this, e = new BusinessRulesEventArgs<ProductModel>() { Items= result, FilterExpressionString  = predicateString });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
		public List<ProductModel> GetBy(Expression<Func<ProductModel, bool>> predicate, bool loadRelations, ContextRequest contextRequest)
        {
			if(!loadRelations)
				return GetBy(predicate, contextRequest);
			else
				return GetBy(predicate, contextRequest, "Products,ProductModelProductDescriptions");

        }

        public List<ProductModel> GetBy(Expression<Func<ProductModel, bool>> predicate, int? pageSize, int? page, string orderBy, SFSdotNet.Framework.Data.SortDirection? sortDirection)
        {
            return GetBy(predicate, new ContextRequest() { CustomQuery = new CustomQuery() { Page = page, PageSize = pageSize, OrderBy = orderBy, SortDirection = sortDirection } });
        }
        public List<ProductModel> GetBy(Expression<Func<ProductModel, bool>> predicate)
        {
		
			ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = null;
            return this.GetBy(predicate, contextRequest, "");
        }
        #endregion
        #region Dynamic String
		private string GetSpecificFilter(string filter) {
            string result = "";
		    string linqFilter = String.Empty;
            string freeTextFilter = String.Empty;
            if (filter.Contains("|"))
            {
                linqFilter = filter.Split(char.Parse("|"))[0];
                freeTextFilter = filter.Split(char.Parse("|"))[1];
            }
 			else {
                linqFilter = filter;
            }
            string specificFilter = linqFilter;
            if (!string.IsNullOrEmpty(freeTextFilter))
            {
                System.Text.StringBuilder sbCont = new System.Text.StringBuilder();
                if (specificFilter.Length > 0)
                {
                    sbCont.Append(" AND ");
                    sbCont.Append(" ({0})");
                }
                else
                {
                    sbCont.Append("{0}");
                }
                var words = freeTextFilter.Split(char.Parse(" "));
                System.Text.StringBuilder sbSpec = new System.Text.StringBuilder();
                 int nWords = 1;
				foreach (var word in words)
                {
                    if (sbSpec.Length > 0) sbSpec.Append(" AND ");
                    sbSpec.Append("(");
					
	
					
											
					sbSpec.Append(string.Format(@"Name.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"CatalogDescription.Contains(""{0}"")", word));

					
	
					
	
					
			
                    sbSpec.Append(")");
					
					nWords++;

                }
                specificFilter = string.Format("{0}{1}", specificFilter, string.Format(sbCont.ToString(), sbSpec.ToString()));
            }
			result = specificFilter;
			
			return result;

		}
		public List<ProductModel> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params object[] extraParams)
        {
        	string specificFilter = "";
            if (!string.IsNullOrEmpty(filter))
              specificFilter=  GetSpecificFilter(filter);
            if (string.IsNullOrEmpty(orderBy))
            {
			                orderBy = "Name";
            }
			SFSdotNet.Framework.Data.SortDirection direction = SFSdotNet.Framework.Data.SortDirection.Ascending;
            if (!string.IsNullOrEmpty(orderDir))
            {
                if (orderDir == "desc")
                    direction = SFSdotNet.Framework.Data.SortDirection.Descending;
            }
            return BR.ProductModelsBR.Instance.GetBy(specificFilter,
                new SFSdotNet.Framework.My.ContextRequest()
                {
                    CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
                    {
						ExtraParams= extraParams,
               
                        OrderBy = orderBy,
                        SortDirection = direction,
                        Page = page,
                        PageSize = pageSize
                    }
                });
        }


        public List<ProductModel> GetBy(string strWhere, ContextRequest contextRequest)
        {
        	#region old code
				Expression<Func<ProductModel, bool>> predicate = null;
                if (!string.IsNullOrEmpty(strWhere)){

                    object[] extraParams = null;
                    if (contextRequest != null )
                        if (contextRequest.CustomQuery != null )
                            extraParams = contextRequest.CustomQuery.ExtraParams;
                    predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductModel, bool>(strWhere, extraParams);				}
				 if (contextRequest == null)
                {
                    contextRequest = new ContextRequest();
                    if (contextRequest.CustomQuery == null)
                        contextRequest.CustomQuery = new CustomQuery();
                }
                
            contextRequest.CustomQuery.FilterExpressionString = strWhere;
				//return GetBy(predicate, contextRequest);  

			#endregion				
				
                    return GetBy(strWhere, contextRequest, "");  


        }
       public List<ProductModel> GetBy(string strWhere)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
			
            return GetBy(strWhere, context, null);
        }

        public List<ProductModel> GetBy(string strWhere, string includes)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
            return GetBy(strWhere, context, includes);
        }

        #endregion
        #endregion
		
		  #region SaveOrUpdate
        private ProductModel Save(ProductModel entity, bool saveChanges, EFPocoContext con)
        {
				ObjectContext context = null;
            return Update(entity, saveChanges, out context);

			
        }

 		 public ProductModel Create(ProductModel entity)
        {
				ObjectContext context = null;
				return this.Create(entity, true, out context);

        }
         public ProductModel Create(ProductModel entity, bool saveChanges, out ObjectContext context)
        {
                    return Create(entity, saveChanges , out context, null);
        }
         public ProductModel Create(ProductModel entity, params Expression<Func<ProductModel,object>>[] paths)
        {
            ObjectContext context = null;
            if(paths != null)
				return Create(entity, true, out context, paths);
			else 
				return Create(entity, true, out context);
        }
        public ProductModel Create(ProductModel entity, bool saveChanges, out ObjectContext context, params Expression<Func<ProductModel,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				ProductModel itemResult = null;
#region Autos
	

			entity.rowguid = Guid.NewGuid();
	
	

#endregion
                e = null;
                OnCreating(this,e = new BusinessRulesEventArgs<ProductModel>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							context = null;
							return e.Item;

						}
					}



				ProductModelAdapter adapter = con.GetAdapterObject<ProductModelAdapter>(entity);;
				List<Expression<Func<ProductModelAdapter, object>>> paths = new List<Expression<Func<ProductModelAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(ProductModelAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<ProductModelAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "Products":
								path = p => p.Products.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.Products.First().ProductCategory.WithoutUpdate();											
							break;
                        
							case "ProductModelProductDescriptions":
								path = p => p.ProductModelProductDescriptions.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.ProductModelProductDescriptions.First().ProductDescription.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        
                       paths.Add(path.Expand());
                    }
                }
                object aux = null;
					//paths = pathBuilder.ToArray();

#region Childs Products 
				if (adapter.Products != null)
                {
                    foreach (var item in adapter.Products)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("Products", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.Products.First().WithoutUpdate());
								
						if (item.ProductCategory != null){
							item.ProductCategory.EntityKey = con.WrappedContext.CreateEntityKey("ProductCategories", item.ProductCategory);
                            
             
						}								
							if (item.ProductModel == null)
								item.ProductModel = adapter;

								item.EntityKey = null;
							}

                    }
					if (adapter.Products.Count > 0){
						paths.Add(p => p.Products.First().WithoutUpdate());
						paths.Add(p => p.Products.First().ProductCategory.WithoutUpdate());
					
					}
                }
#endregion 

#region Childs ProductModelProductDescriptions 
				if (adapter.ProductModelProductDescriptions != null)
                {
                    foreach (var item in adapter.ProductModelProductDescriptions)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("ProductModelProductDescriptions", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.ProductModelProductDescriptions.First().WithoutUpdate());
								
						if (item.ProductDescription != null){
							item.ProductDescription.EntityKey = con.WrappedContext.CreateEntityKey("ProductDescriptions", item.ProductDescription);
                            
             
						}								
							if (item.ProductModel == null)
								item.ProductModel = adapter;

								item.EntityKey = null;
							}

                    }
					if (adapter.ProductModelProductDescriptions.Count > 0){
						paths.Add(p => p.ProductModelProductDescriptions.First().WithoutUpdate());
						paths.Add(p => p.ProductModelProductDescriptions.First().ProductDescription.WithoutUpdate());
					
					}
                }
#endregion 




                //con.WrappedContext.AttachObjectGraph<ProductModelAdapter>(adapter, p=>p.Products, p=>p.ProductModelProductDescriptions);
                con.WrappedContext.AttachObjectGraph<ProductModelAdapter>(adapter, paths.ToArray());
              	if (saveChanges){
                    con.WrappedContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
					 
				}
                else
                    con.WrappedContext.SaveChanges(SaveOptions.None);
                if (!saveChanges)
                    context = con.WrappedContext;
                else
                    context = null;
				itemResult = adapter.PocoEntity;
                OnCreated(this, e = new BusinessRulesEventArgs<ProductModel>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });
                return itemResult;
            }
        }
        BusinessRulesEventArgs<ProductModel> e = null;
        public void Create(List<ProductModel> entities)
        {
				ObjectContext context = null;
				foreach (ProductModel entity in entities)
				{
					this.Create(entity, true, out context);
				}

				
				
        }

        public ProductModel Update(ProductModel entity)
        {
			ObjectContext context = null;
            return Update(entity, true, out context, null);

        }
         public ProductModel Update(ProductModel entity, params Expression<Func<ProductModel, object>>[] paths)
        {
			  ObjectContext context = null;
            return Update(entity, true, out context, paths);
         }
        public ProductModel Update(ProductModel entity, bool saveChanges, out ObjectContext outcontext)
        {
			return Update(entity, saveChanges, out outcontext, null);
		}
         public ProductModel Update(ProductModel entity, bool saveChanges, out ObjectContext outcontext, params Expression<Func<ProductModel,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				ProductModel  itemResult = null;

	

				e = null;
                OnUpdating(this,e = new BusinessRulesEventArgs<ProductModel>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							outcontext = null;
							return e.Item;

						}
					}

                ProductModelAdapter adapter = con.GetAdapterObject<ProductModelAdapter>(entity);
                adapter.EntityKey = con.WrappedContext.CreateEntityKey("ProductModels", adapter);
				    var es = con.ProductModels;
				List<Expression<Func<ProductModelAdapter, object>>> paths = new List<Expression<Func<ProductModelAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(ProductModelAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<ProductModelAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "Products":
								//path = p => member;
								path = p => p.Products.First().WithoutUpdate();
				//				path = p => p.Products.First().ProductCategory.WithoutUpdate();											
							break;
                        
							case "ProductModelProductDescriptions":
								//path = p => member;
								path = p => p.ProductModelProductDescriptions.First().WithoutUpdate();
				//				path = p => p.ProductModelProductDescriptions.First().ProductDescription.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        paths.Add(path.Expand());
 					}
                }
                else {
                  paths = new List<Expression<Func<ProductModelAdapter, object>>>();

					//List<Expression<Func<ProductModelAdapter,object>>> pathBuilder = new List<Expression<Func<ProductModelAdapter,object>>>();
		
					//paths = pathBuilder.ToArray();		
			}
			object aux = null;
				if (adapter.Products != null)
                {
                    foreach (var item in adapter.Products)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("Products", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }
				if (adapter.ProductModelProductDescriptions != null)
                {
                    foreach (var item in adapter.ProductModelProductDescriptions)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("ProductModelProductDescriptions", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }



                //con.AttachObjectGraph<ProductModel>(adapter, p=>p.Products, p=>p.ProductModelProductDescriptions);
                con.WrappedContext.AttachObjectGraph<ProductModelAdapter>(adapter, paths.ToArray());
				if (saveChanges){
                	con.WrappedContext.SaveChanges();
					 
					}
                if(!saveChanges)
					outcontext = con.WrappedContext;
				else
					outcontext = null;
				itemResult = adapter.PocoEntity;
				OnUpdated(this, e = new BusinessRulesEventArgs<ProductModel>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });

              	return itemResult;

			  }
        }
        public ProductModel Save(ProductModel entity)
        {
			return Save(entity, true, null);
        }
        public int Save(List<ProductModel> entities)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
			
            int n = 0;
            foreach (ProductModel item in entities)
            {
                try
                {
                    this.Save(item, false, con);
                    n++;
                }catch (Exception ex){
                    SFSdotNet.Framework.My.EventLog.Exception(ex);
                }
            }
            con.SaveChanges();
            return n;
            }
        }
        #endregion
        #region Delete
        public void Delete(ProductModel entity)
        {
				ObjectContext context = null;
				this.Delete(entity, true, out context);
			
        }

        
        public void Delete(ProductModel entity, bool saveChanges, out  ObjectContext context)
        {
			using (EFPocoContext _con = new EFPocoContext())
			{
				int result = 0;
				
               	BusinessRulesEventArgs<ProductModel> _e = null;
                OnDeleting(this,_e = new BusinessRulesEventArgs<ProductModel>() { Item=entity, SaveChanges =saveChanges });
				   if (_e != null) {
						if (_e.Cancel)
						{
							context = null;
							return;

						}
					}


				ProductModelAdapter adapter = _con.GetAdapterObject<ProductModelAdapter>(entity);
                adapter.EntityKey = _con.WrappedContext.CreateEntityKey("ProductModels", adapter);
                
	            //adapter = _con.WrappedContext.AttachObjectGraph<ProductModelAdapter>(adapter);
				_con.WrappedContext.AttachTo("ProductModels", adapter);
                
									_con.WrappedContext.DeleteObject(adapter);
                				
				if (!saveChanges)
                    context = _con.WrappedContext;
                else
                    context = null;
				 SaveOptions saveOption = SaveOptions.None;
                if (saveChanges)
                    saveOption = SaveOptions.AcceptAllChangesAfterSave;

				result = _con.WrappedContext.SaveChanges(saveOption);
				if (saveChanges){
					
					}
				if (_e == null)
					_e = new BusinessRulesEventArgs<ProductModel>() { Item = entity };
                OnDeleted(this, _e );

				//return null;
			}            
        }
        public void Delete(List<ProductModel> entities)
        {
				ObjectContext context = null;
			
				foreach (ProductModel item in entities)
				{
					this.Delete(item, true, out context);
				}
			

			
        }
        #endregion
 
        #region GetCount
        public int GetCount(Expression<Func<ProductModel, bool>> predicate)
        {
		
			using (EFPocoContext con = new EFPocoContext())
			{


				if (predicate == null) predicate = PredicateBuilder.True<ProductModel>();
				
				return con.ProductModels.Count(predicate);
			}

        }
        public int GetCount(string predicate)
        {
			e = null;
            OnCounting(this, e = new BusinessRulesEventArgs<ProductModel>() {  FilterExpressionString = predicate });
            if (e != null)
            {
                if (e.Cancel)
                {
                    context = null;
                    return e.CountResult;

                }
                predicate = e.FilterExpressionString;
            
            }
					predicate = GetSpecificFilter(predicate);
			using (EFContext con = new EFContext())
			{
				   
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicate, ref predicateWithManyRelations, ref predicateWithFKAndComputed);

                if (!string.IsNullOrEmpty(predicate))
                {
				
					
                    return con.ProductModels.Count(System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductModel, bool>(predicate));
					
                }else
                    return con.ProductModels.Count();

			}

		}
         public int GetCount()
        {
            return GetCount(p => true);
        }
        #endregion
        
         public ProductModel Update(ProductModel entity, string paths)
        {
            return Update(entity, paths.Split(char.Parse(",")));
            
        }

        public ProductModel Update(ProductModel entity, string[] paths)
        {
            // Translate
            List<Expression<Func<ProductModel, object>>> pathList = new List<Expression<Func<ProductModel, object>>>();
            for (int i = 0; i <= paths.Length -1; i++)
            {
                var param = Expression.Parameter(typeof(ProductModel), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<ProductModel, object>> path = p => member;
                pathList.Add(path.Expand());
            }
           return Update(entity, pathList.ToArray());
        }

        public void Update(List<ProductModel> entities, string paths)
        {
            foreach (var entity in entities )
            {
                Update(entity, paths);
            }
        }

        public ProductModel Create(ProductModel entity, string paths)
        {
			if(string.IsNullOrEmpty(paths))
				return Create(entity);
				
            return Create(entity, paths.Split(char.Parse(",")));
        }

        public  void Create(List<ProductModel> entities, string paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }

        public void Create(List<ProductModel> entities, string[] paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }
        
        public ProductModel  Create(ProductModel entity, string[] paths)
        {
            List<Expression<Func<ProductModel, object>>> pathList = new List<Expression<Func<ProductModel, object>>>();
            for (int i = 0; i < paths.Length - 1; i++)
            {
                var param = Expression.Parameter(typeof(ProductModel), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<ProductModel, object>> path = p => member;
                pathList.Add(path.Expand());
            }
            return Create(entity, pathList.ToArray());
        }
        public void Delete(List<ProductModel.CompositeKey> entityKeys)
        {

            List<ProductModel> items = new List<ProductModel>();
            foreach (var itemKey in entityKeys)
            {
                items.Add(GetByKey(itemKey.ProductModelID));
            }

            Delete(items);

        }
		
		
	}
		public partial class ProductModelProductDescriptionsBR{
	 	
           
		 #region Partial methods

           partial void OnUpdating(object sender, BusinessRulesEventArgs<ProductModelProductDescription> e);

            partial void OnUpdated(object sender, BusinessRulesEventArgs<ProductModelProductDescription> e);

            partial void OnCreating(object sender, BusinessRulesEventArgs<ProductModelProductDescription> e);
            partial void OnCreated(object sender, BusinessRulesEventArgs<ProductModelProductDescription> e);

            partial void OnDeleting(object sender, BusinessRulesEventArgs<ProductModelProductDescription> e);
            partial void OnDeleted(object sender, BusinessRulesEventArgs<ProductModelProductDescription> e);

            partial void OnGetting(object sender, BusinessRulesEventArgs<ProductModelProductDescription> e);
            partial void OnTaken(object sender, BusinessRulesEventArgs<ProductModelProductDescription> e);
            partial void OnCounting(object sender, BusinessRulesEventArgs<ProductModelProductDescription> e);
 
 
            #endregion
			
		private static ProductModelProductDescriptionsBR singlenton =null;
				public static ProductModelProductDescriptionsBR NewInstance(){
					return  new ProductModelProductDescriptionsBR();
					
				}
		public static ProductModelProductDescriptionsBR Instance{
			get{
				if (singlenton == null)
					singlenton = new ProductModelProductDescriptionsBR();
				return singlenton;
			}
		}
		private bool preventSecurityRestrictions = false;

		#region Fields
        EFPocoContext context = null;
        #endregion
        #region Constructor
        public ProductModelProductDescriptionsBR()
        {
            context = new EFPocoContext();
        }
		 public ProductModelProductDescriptionsBR(bool preventSecurity)
            {
                this.preventSecurityRestrictions = preventSecurity;
				context = new EFPocoContext();
            }
        #endregion
		
		#region Get

 		public IQueryable<ProductModelProductDescription> Get()
        {
            //using (EFContext con = new EFContext())
            //{
				EFContext con = new EFContext();
                var query = con.ProductModelProductDescriptions.AsQueryable();
                con.ContextOptions.ProxyCreationEnabled = false;

                //query = ContextQueryBuilder<Nutrient>.ApplyContextQuery(query, contextRequest);

                return query;




            //}

        }
		
		public List<ProductModelProductDescription> GetAll()
        {
            return this.GetBy(p => true);
        }
        public List<ProductModelProductDescription> GetAll(string includes)
        {
            return this.GetBy(p => true, includes);
        }
        public ProductModelProductDescription GetByKey(Int32 productModelID, Int32 productDescriptionID, String culture)
        {
            return GetByKey(productModelID, productDescriptionID, culture, true);
        }
        public ProductModelProductDescription GetByKey(Int32 productModelID, Int32 productDescriptionID, String culture, bool loadIncludes)
        {
            ProductModelProductDescription item = null;
			var query = PredicateBuilder.True<ProductModelProductDescription>();
                    
			string strWhere = "ProductModelID = " + productModelID.ToString()+ " And " + "ProductDescriptionID = " + productDescriptionID.ToString()+ " And " + "Culture = " + culture.ToString();
            Expression<Func<ProductModelProductDescription, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductModelProductDescription, bool>(strWhere);
			
			 ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = strWhere;

			//item = GetBy(predicate, loadIncludes, contextRequest).FirstOrDefault();
			item = GetBy(strWhere,loadIncludes,contextRequest).FirstOrDefault();
            return item;
        }
         public List<ProductModelProductDescription> GetBy(string strWhere, bool loadRelations, ContextRequest contextRequest)
        {
            if (!loadRelations)
                return GetBy(strWhere, contextRequest);
            else
                return GetBy(strWhere, contextRequest, "");

        }
		  public List<ProductModelProductDescription> GetBy(string strWhere, bool loadRelations)
        {
              if (!loadRelations)
                return GetBy(strWhere, new ContextRequest());
            else
                return GetBy(strWhere, new ContextRequest(), "");

        }
         public ProductModelProductDescription GetByKey(Int32 productModelID, Int32 productDescriptionID, String culture, params Expression<Func<ProductModelProductDescription, object>>[] includes)
        {
            ProductModelProductDescription item = null;
			string strWhere = "ProductModelID = " + productModelID.ToString()+ " And " + "ProductDescriptionID = " + productDescriptionID.ToString()+ " And " + "Culture = " + culture.ToString();
          Expression<Func<ProductModelProductDescription, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductModelProductDescription, bool>(strWhere);
			
        item = GetBy(predicate, includes).FirstOrDefault();
         ////   item = GetBy(strWhere,includes).FirstOrDefault();
			return item;

        }
        public ProductModelProductDescription GetByKey(Int32 productModelID, Int32 productDescriptionID, String culture, string includes)
        {
            ProductModelProductDescription item = null;
			string strWhere = "ProductModelID = " + productModelID.ToString()+ " And " + "ProductDescriptionID = " + productDescriptionID.ToString()+ " And " + "Culture = " + culture.ToString();
            
			
            item = GetBy(strWhere, includes).FirstOrDefault();
            return item;

        }

        #region Dynamic Predicate
        public List<ProductModelProductDescription> GetBy(Expression<Func<ProductModelProductDescription, bool>> predicate, int? pageSize, int? page)
        {
            return this.GetBy(predicate, pageSize, page, null, null);
        }
        public List<ProductModelProductDescription> GetBy(Expression<Func<ProductModelProductDescription, bool>> predicate, ContextRequest contextRequest)
        {

            return GetBy(predicate, contextRequest,"");
        }
        
        public List<ProductModelProductDescription> GetBy(Expression<Func<ProductModelProductDescription, bool>> predicate, ContextRequest contextRequest, params Expression<Func<ProductModelProductDescription, object>>[] includes)
        {
            StringBuilder sb = new StringBuilder();
           if (includes != null)
            {
                foreach (var path in includes)
                {

						if (sb.Length > 0) sb.Append(",");
						sb.Append(SFSdotNet.Framework.Linq.Utils.IncludeToString<ProductModelProductDescription>(path));

               }
            }
            return GetBy(predicate, contextRequest, sb.ToString());
        }
        
        
        public List<ProductModelProductDescription> GetBy(Expression<Func<ProductModelProductDescription, bool>> predicate, string includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";

            return GetBy(predicate, context, includes);
        }

        public List<ProductModelProductDescription> GetBy(Expression<Func<ProductModelProductDescription, bool>> predicate, params Expression<Func<ProductModelProductDescription, object>>[] includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";
            return GetBy(predicate, context, includes);
        }

      
		public bool DisableCache { get; set; }
		 public List<ProductModelProductDescription> GetBy(Expression<Func<ProductModelProductDescription, bool>> predicate, ContextRequest contextRequest, string includes)
        {
            using (EFPocoContext con = new EFPocoContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;

				List<ProductModelProductDescription> result = null;
                 e = null;
                OnGetting(con,e = new BusinessRulesEventArgs<ProductModelProductDescription>() { FilterExpression = predicate, ContextRequest = contextRequest, FilterExpressionString = contextRequest.CustomQuery.FilterExpressionString});
				   if (e != null) {
				    predicate = e.FilterExpression;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				con.EnableChangeTrackingUsingProxies = false;
				con.WrappedContext.ProductModelProductDescriptions.MergeOption = MergeOption.NoTracking;
                con.WrappedContext.ContextOptions.ProxyCreationEnabled = false;
                if (predicate == null) predicate = PredicateBuilder.True<ProductModelProductDescription>();
 				string fkIncludes = "ProductDescription,ProductModel";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.ProductModelProductDescriptions;
				 
                IQueryable<ProductModelProductDescription> query = es.AsQueryable();

                                if (!string.IsNullOrEmpty(includes))
                {
                    foreach (string include in includes.Split(char.Parse(",")))
                    {
						if (!string.IsNullOrEmpty(include))
                            query = query.Include(include);
                    }
                }
				query =query.Where(predicate);
                query = ContextQueryBuilder<ProductModelProductDescription>.ApplyContextQuery(query, contextRequest);

                result = query.ToList<ProductModelProductDescription>();
				e = null;
				OnTaken(this, e = new BusinessRulesEventArgs<ProductModelProductDescription>() { Items= result, FilterExpression = predicate });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
        public List<ProductModelProductDescription> GetBy(string predicateString, ContextRequest contextRequest, string includes)
        {
            using (EFContext con = new EFContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;


				List<ProductModelProductDescription> result = null;
                 e = null;
                  OnGetting(con,e = new BusinessRulesEventArgs<ProductModelProductDescription>() {  ContextRequest = contextRequest, FilterExpressionString = predicateString });
			   	if (e != null) {
				    predicateString = e.FilterExpressionString;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				//con.EnableChangeTrackingUsingProxies = false;
				con.ProductModelProductDescriptions.MergeOption = MergeOption.NoTracking;
                con.ContextOptions.ProxyCreationEnabled = false;
                //if (predicate == null) predicate = PredicateBuilder.True<ProductModelProductDescription>();
 				string fkIncludes = "ProductDescription,ProductModel";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}else{
                    contextRequest = new ContextRequest();
                    contextRequest.CustomQuery = new CustomQuery();

                }
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.ProductModelProductDescriptions;
				IQueryable<ProductModelProductDescription> query = es.AsQueryable();

		
				// include relations FK
				if(string.IsNullOrEmpty(includes) ){
					includes ="";
				}
				bool includeProductDescription = includes.Split(char.Parse(",")).Contains("ProductDescription");

				bool includeProductModel = includes.Split(char.Parse(",")).Contains("ProductModel");

				
				//string predicateString = predicate.ToDynamicLinq<ProductModelProductDescription>();
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicateString, ref predicateWithManyRelations, ref predicateWithFKAndComputed);
                var _queryable = query.AsQueryable();
                if (!string.IsNullOrEmpty(predicateWithManyRelations))
                    _queryable = _queryable.Where(predicateWithManyRelations);
 
				var  queryable = _queryable.Select(                    
				p => 
                        new
                    {
					ProductModelID = p.ProductModelID
,ProductDescriptionID = p.ProductDescriptionID
,Culture = p.Culture
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

,ProductDescription = includeProductDescription ? p.ProductDescription:null
,ProductModel = includeProductModel ? p.ProductModel:null


	
                    }
                    
                    );
					
				
                    if (!string.IsNullOrEmpty(predicateWithFKAndComputed))
                        queryable = queryable.Where(predicateWithFKAndComputed, contextRequest.CustomQuery.ExtraParams);

				QueryComplementOptions queryOps = ContextQueryBuilder.ApplyContextQuery(contextRequest);
            	if (!string.IsNullOrEmpty(queryOps.OrderByAndSort))
					queryable = queryable.OrderBy(queryOps.OrderByAndSort);
               	if (queryOps.Skip != null)
                {
                    queryable = queryable.Skip(queryOps.Skip.Value);
                }
                if (queryOps.PageSize != null)
                {
                    queryable = queryable.Take (queryOps.PageSize.Value);
                }
                result = queryable.AsEnumerable().
                    Select(
                    p =>  new ProductModelProductDescription()
                    {
					ProductModelID = p.ProductModelID
,ProductDescriptionID = p.ProductDescriptionID
,Culture = p.Culture
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate
,ProductDescription = p.ProductDescription
,ProductModel = p.ProductModel

                    }
                     ).ToList();

				e = null;
			OnTaken(this, e = new BusinessRulesEventArgs<ProductModelProductDescription>() { Items= result, FilterExpressionString  = predicateString });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
		public List<ProductModelProductDescription> GetBy(Expression<Func<ProductModelProductDescription, bool>> predicate, bool loadRelations, ContextRequest contextRequest)
        {
			if(!loadRelations)
				return GetBy(predicate, contextRequest);
			else
				return GetBy(predicate, contextRequest, "");

        }

        public List<ProductModelProductDescription> GetBy(Expression<Func<ProductModelProductDescription, bool>> predicate, int? pageSize, int? page, string orderBy, SFSdotNet.Framework.Data.SortDirection? sortDirection)
        {
            return GetBy(predicate, new ContextRequest() { CustomQuery = new CustomQuery() { Page = page, PageSize = pageSize, OrderBy = orderBy, SortDirection = sortDirection } });
        }
        public List<ProductModelProductDescription> GetBy(Expression<Func<ProductModelProductDescription, bool>> predicate)
        {
		
			ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = null;
            return this.GetBy(predicate, contextRequest, "");
        }
        #endregion
        #region Dynamic String
		private string GetSpecificFilter(string filter) {
            string result = "";
		    string linqFilter = String.Empty;
            string freeTextFilter = String.Empty;
            if (filter.Contains("|"))
            {
                linqFilter = filter.Split(char.Parse("|"))[0];
                freeTextFilter = filter.Split(char.Parse("|"))[1];
            }
 			else {
                linqFilter = filter;
            }
            string specificFilter = linqFilter;
            if (!string.IsNullOrEmpty(freeTextFilter))
            {
                System.Text.StringBuilder sbCont = new System.Text.StringBuilder();
                if (specificFilter.Length > 0)
                {
                    sbCont.Append(" AND ");
                    sbCont.Append(" ({0})");
                }
                else
                {
                    sbCont.Append("{0}");
                }
                var words = freeTextFilter.Split(char.Parse(" "));
                System.Text.StringBuilder sbSpec = new System.Text.StringBuilder();
                 int nWords = 1;
				foreach (var word in words)
                {
                    if (sbSpec.Length > 0) sbSpec.Append(" AND ");
                    sbSpec.Append("(");
					
	
					
	
					
											
					sbSpec.Append(string.Format(@"Culture.Contains(""{0}"")", word));

					
	
					
	
					
	
					
	
					
			
                    sbSpec.Append(")");
					
					nWords++;

                }
                specificFilter = string.Format("{0}{1}", specificFilter, string.Format(sbCont.ToString(), sbSpec.ToString()));
            }
			result = specificFilter;
			
			return result;

		}
		public List<ProductModelProductDescription> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params object[] extraParams)
        {
        	string specificFilter = "";
            if (!string.IsNullOrEmpty(filter))
              specificFilter=  GetSpecificFilter(filter);
            if (string.IsNullOrEmpty(orderBy))
            {
			                orderBy = "ProductModelID";
            }
			SFSdotNet.Framework.Data.SortDirection direction = SFSdotNet.Framework.Data.SortDirection.Ascending;
            if (!string.IsNullOrEmpty(orderDir))
            {
                if (orderDir == "desc")
                    direction = SFSdotNet.Framework.Data.SortDirection.Descending;
            }
            return BR.ProductModelProductDescriptionsBR.Instance.GetBy(specificFilter,
                new SFSdotNet.Framework.My.ContextRequest()
                {
                    CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
                    {
						ExtraParams= extraParams,
               
                        OrderBy = orderBy,
                        SortDirection = direction,
                        Page = page,
                        PageSize = pageSize
                    }
                });
        }


        public List<ProductModelProductDescription> GetBy(string strWhere, ContextRequest contextRequest)
        {
        	#region old code
				Expression<Func<ProductModelProductDescription, bool>> predicate = null;
                if (!string.IsNullOrEmpty(strWhere)){

                    object[] extraParams = null;
                    if (contextRequest != null )
                        if (contextRequest.CustomQuery != null )
                            extraParams = contextRequest.CustomQuery.ExtraParams;
                    predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductModelProductDescription, bool>(strWhere, extraParams);				}
				 if (contextRequest == null)
                {
                    contextRequest = new ContextRequest();
                    if (contextRequest.CustomQuery == null)
                        contextRequest.CustomQuery = new CustomQuery();
                }
                
            contextRequest.CustomQuery.FilterExpressionString = strWhere;
				//return GetBy(predicate, contextRequest);  

			#endregion				
				
                    return GetBy(strWhere, contextRequest, "");  


        }
       public List<ProductModelProductDescription> GetBy(string strWhere)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
			
            return GetBy(strWhere, context, null);
        }

        public List<ProductModelProductDescription> GetBy(string strWhere, string includes)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
            return GetBy(strWhere, context, includes);
        }

        #endregion
        #endregion
		
		  #region SaveOrUpdate
        private ProductModelProductDescription Save(ProductModelProductDescription entity, bool saveChanges, EFPocoContext con)
        {
				ObjectContext context = null;
            return Update(entity, saveChanges, out context);

			
        }

 		 public ProductModelProductDescription Create(ProductModelProductDescription entity)
        {
				ObjectContext context = null;
				return this.Create(entity, true, out context);

        }
         public ProductModelProductDescription Create(ProductModelProductDescription entity, bool saveChanges, out ObjectContext context)
        {
                    return Create(entity, saveChanges , out context, null);
        }
         public ProductModelProductDescription Create(ProductModelProductDescription entity, params Expression<Func<ProductModelProductDescription,object>>[] paths)
        {
            ObjectContext context = null;
            if(paths != null)
				return Create(entity, true, out context, paths);
			else 
				return Create(entity, true, out context);
        }
        public ProductModelProductDescription Create(ProductModelProductDescription entity, bool saveChanges, out ObjectContext context, params Expression<Func<ProductModelProductDescription,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				ProductModelProductDescription itemResult = null;
#region Autos
	

			entity.rowguid = Guid.NewGuid();
	
	

#endregion
                e = null;
                OnCreating(this,e = new BusinessRulesEventArgs<ProductModelProductDescription>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							context = null;
							return e.Item;

						}
					}



				ProductModelProductDescriptionAdapter adapter = con.GetAdapterObject<ProductModelProductDescriptionAdapter>(entity);;
				List<Expression<Func<ProductModelProductDescriptionAdapter, object>>> paths = new List<Expression<Func<ProductModelProductDescriptionAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(ProductModelProductDescriptionAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<ProductModelProductDescriptionAdapter, object>> path  = null;
                        switch(member.Member.Name){
							
							default:
								path = p => member;
							break;
                        }

                        
                       paths.Add(path.Expand());
                    }
                }
                object aux = null;
					paths.Add(p => p.ProductDescription.WithoutUpdate());

					paths.Add(p => p.ProductModel.WithoutUpdate());

					//paths = pathBuilder.ToArray();

				if (adapter.ProductDescription != null ){
					if(adapter.ProductDescription.EntityKey == null) adapter.ProductDescription.EntityKey = con.WrappedContext.CreateEntityKey("ProductDescriptions", adapter.ProductDescription);
				}
				if (adapter.ProductModel != null ){
					if(adapter.ProductModel.EntityKey == null) adapter.ProductModel.EntityKey = con.WrappedContext.CreateEntityKey("ProductModels", adapter.ProductModel);
				}



                //con.WrappedContext.AttachObjectGraph<ProductModelProductDescriptionAdapter>(adapter, p=>p.ProductDescription, p=>p.ProductModel);
                con.WrappedContext.AttachObjectGraph<ProductModelProductDescriptionAdapter>(adapter, paths.ToArray());
              	if (saveChanges){
                    con.WrappedContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
					 
				}
                else
                    con.WrappedContext.SaveChanges(SaveOptions.None);
                if (!saveChanges)
                    context = con.WrappedContext;
                else
                    context = null;
				itemResult = adapter.PocoEntity;
                OnCreated(this, e = new BusinessRulesEventArgs<ProductModelProductDescription>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });
                return itemResult;
            }
        }
        BusinessRulesEventArgs<ProductModelProductDescription> e = null;
        public void Create(List<ProductModelProductDescription> entities)
        {
				ObjectContext context = null;
				foreach (ProductModelProductDescription entity in entities)
				{
					this.Create(entity, true, out context);
				}

				
				
        }

        public ProductModelProductDescription Update(ProductModelProductDescription entity)
        {
			ObjectContext context = null;
            return Update(entity, true, out context, null);

        }
         public ProductModelProductDescription Update(ProductModelProductDescription entity, params Expression<Func<ProductModelProductDescription, object>>[] paths)
        {
			  ObjectContext context = null;
            return Update(entity, true, out context, paths);
         }
        public ProductModelProductDescription Update(ProductModelProductDescription entity, bool saveChanges, out ObjectContext outcontext)
        {
			return Update(entity, saveChanges, out outcontext, null);
		}
         public ProductModelProductDescription Update(ProductModelProductDescription entity, bool saveChanges, out ObjectContext outcontext, params Expression<Func<ProductModelProductDescription,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				ProductModelProductDescription  itemResult = null;

	

				e = null;
                OnUpdating(this,e = new BusinessRulesEventArgs<ProductModelProductDescription>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							outcontext = null;
							return e.Item;

						}
					}

                ProductModelProductDescriptionAdapter adapter = con.GetAdapterObject<ProductModelProductDescriptionAdapter>(entity);
                adapter.EntityKey = con.WrappedContext.CreateEntityKey("ProductModelProductDescriptions", adapter);
				    var es = con.ProductModelProductDescriptions;
				List<Expression<Func<ProductModelProductDescriptionAdapter, object>>> paths = new List<Expression<Func<ProductModelProductDescriptionAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(ProductModelProductDescriptionAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<ProductModelProductDescriptionAdapter, object>> path  = null;
                        switch(member.Member.Name){
							
							default:
								path = p => member;
							break;
                        }

                        paths.Add(path.Expand());
 					}
                }
                else {
                  paths = new List<Expression<Func<ProductModelProductDescriptionAdapter, object>>>();

					//List<Expression<Func<ProductModelProductDescriptionAdapter,object>>> pathBuilder = new List<Expression<Func<ProductModelProductDescriptionAdapter,object>>>();
					paths.Add(p => p.ProductDescription.WithoutUpdate());

					paths.Add(p => p.ProductModel.WithoutUpdate());

		
					//paths = pathBuilder.ToArray();		
			}
			object aux = null;
				if (adapter.ProductDescription != null ){
					if(adapter.ProductDescription.EntityKey == null) adapter.ProductDescription.EntityKey = con.WrappedContext.CreateEntityKey("ProductDescriptions", adapter.ProductDescription);
				}

                
				if (adapter.ProductModel != null ){
					if(adapter.ProductModel.EntityKey == null) adapter.ProductModel.EntityKey = con.WrappedContext.CreateEntityKey("ProductModels", adapter.ProductModel);
				}

                



                //con.AttachObjectGraph<ProductModelProductDescription>(adapter, p=>p.ProductDescription, p=>p.ProductModel);
                con.WrappedContext.AttachObjectGraph<ProductModelProductDescriptionAdapter>(adapter, paths.ToArray());
				if (saveChanges){
                	con.WrappedContext.SaveChanges();
					 
					}
                if(!saveChanges)
					outcontext = con.WrappedContext;
				else
					outcontext = null;
				itemResult = adapter.PocoEntity;
				OnUpdated(this, e = new BusinessRulesEventArgs<ProductModelProductDescription>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });

              	return itemResult;

			  }
        }
        public ProductModelProductDescription Save(ProductModelProductDescription entity)
        {
			return Save(entity, true, null);
        }
        public int Save(List<ProductModelProductDescription> entities)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
			
            int n = 0;
            foreach (ProductModelProductDescription item in entities)
            {
                try
                {
                    this.Save(item, false, con);
                    n++;
                }catch (Exception ex){
                    SFSdotNet.Framework.My.EventLog.Exception(ex);
                }
            }
            con.SaveChanges();
            return n;
            }
        }
        #endregion
        #region Delete
        public void Delete(ProductModelProductDescription entity)
        {
				ObjectContext context = null;
				this.Delete(entity, true, out context);
			
        }

        
        public void Delete(ProductModelProductDescription entity, bool saveChanges, out  ObjectContext context)
        {
			using (EFPocoContext _con = new EFPocoContext())
			{
				int result = 0;
				
               	BusinessRulesEventArgs<ProductModelProductDescription> _e = null;
                OnDeleting(this,_e = new BusinessRulesEventArgs<ProductModelProductDescription>() { Item=entity, SaveChanges =saveChanges });
				   if (_e != null) {
						if (_e.Cancel)
						{
							context = null;
							return;

						}
					}


				ProductModelProductDescriptionAdapter adapter = _con.GetAdapterObject<ProductModelProductDescriptionAdapter>(entity);
                adapter.EntityKey = _con.WrappedContext.CreateEntityKey("ProductModelProductDescriptions", adapter);
                
	            //adapter = _con.WrappedContext.AttachObjectGraph<ProductModelProductDescriptionAdapter>(adapter);
				_con.WrappedContext.AttachTo("ProductModelProductDescriptions", adapter);
                
									_con.WrappedContext.DeleteObject(adapter);
                				
				if (!saveChanges)
                    context = _con.WrappedContext;
                else
                    context = null;
				 SaveOptions saveOption = SaveOptions.None;
                if (saveChanges)
                    saveOption = SaveOptions.AcceptAllChangesAfterSave;

				result = _con.WrappedContext.SaveChanges(saveOption);
				if (saveChanges){
					
					}
				if (_e == null)
					_e = new BusinessRulesEventArgs<ProductModelProductDescription>() { Item = entity };
                OnDeleted(this, _e );

				//return null;
			}            
        }
        public void Delete(List<ProductModelProductDescription> entities)
        {
				ObjectContext context = null;
			
				foreach (ProductModelProductDescription item in entities)
				{
					this.Delete(item, true, out context);
				}
			

			
        }
        #endregion
 
        #region GetCount
        public int GetCount(Expression<Func<ProductModelProductDescription, bool>> predicate)
        {
		
			using (EFPocoContext con = new EFPocoContext())
			{


				if (predicate == null) predicate = PredicateBuilder.True<ProductModelProductDescription>();
				
				return con.ProductModelProductDescriptions.Count(predicate);
			}

        }
        public int GetCount(string predicate)
        {
			e = null;
            OnCounting(this, e = new BusinessRulesEventArgs<ProductModelProductDescription>() {  FilterExpressionString = predicate });
            if (e != null)
            {
                if (e.Cancel)
                {
                    context = null;
                    return e.CountResult;

                }
                predicate = e.FilterExpressionString;
            
            }
					predicate = GetSpecificFilter(predicate);
			using (EFContext con = new EFContext())
			{
				   
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicate, ref predicateWithManyRelations, ref predicateWithFKAndComputed);

                if (!string.IsNullOrEmpty(predicate))
                {
				
					
                    return con.ProductModelProductDescriptions.Count(System.Linq.Dynamic.DynamicExpression.ParseLambda<ProductModelProductDescription, bool>(predicate));
					
                }else
                    return con.ProductModelProductDescriptions.Count();

			}

		}
         public int GetCount()
        {
            return GetCount(p => true);
        }
        #endregion
        
         public ProductModelProductDescription Update(ProductModelProductDescription entity, string paths)
        {
            return Update(entity, paths.Split(char.Parse(",")));
            
        }

        public ProductModelProductDescription Update(ProductModelProductDescription entity, string[] paths)
        {
            // Translate
            List<Expression<Func<ProductModelProductDescription, object>>> pathList = new List<Expression<Func<ProductModelProductDescription, object>>>();
            for (int i = 0; i <= paths.Length -1; i++)
            {
                var param = Expression.Parameter(typeof(ProductModelProductDescription), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<ProductModelProductDescription, object>> path = p => member;
                pathList.Add(path.Expand());
            }
           return Update(entity, pathList.ToArray());
        }

        public void Update(List<ProductModelProductDescription> entities, string paths)
        {
            foreach (var entity in entities )
            {
                Update(entity, paths);
            }
        }

        public ProductModelProductDescription Create(ProductModelProductDescription entity, string paths)
        {
			if(string.IsNullOrEmpty(paths))
				return Create(entity);
				
            return Create(entity, paths.Split(char.Parse(",")));
        }

        public  void Create(List<ProductModelProductDescription> entities, string paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }

        public void Create(List<ProductModelProductDescription> entities, string[] paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }
        
        public ProductModelProductDescription  Create(ProductModelProductDescription entity, string[] paths)
        {
            List<Expression<Func<ProductModelProductDescription, object>>> pathList = new List<Expression<Func<ProductModelProductDescription, object>>>();
            for (int i = 0; i < paths.Length - 1; i++)
            {
                var param = Expression.Parameter(typeof(ProductModelProductDescription), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<ProductModelProductDescription, object>> path = p => member;
                pathList.Add(path.Expand());
            }
            return Create(entity, pathList.ToArray());
        }
        public void Delete(List<ProductModelProductDescription.CompositeKey> entityKeys)
        {

            List<ProductModelProductDescription> items = new List<ProductModelProductDescription>();
            foreach (var itemKey in entityKeys)
            {
                items.Add(GetByKey(itemKey.ProductModelID, itemKey.ProductDescriptionID, itemKey.Culture));
            }

            Delete(items);

        }
		
		
	}
		public partial class SalesOrderDetailsBR{
	 	
           
		 #region Partial methods

           partial void OnUpdating(object sender, BusinessRulesEventArgs<SalesOrderDetail> e);

            partial void OnUpdated(object sender, BusinessRulesEventArgs<SalesOrderDetail> e);

            partial void OnCreating(object sender, BusinessRulesEventArgs<SalesOrderDetail> e);
            partial void OnCreated(object sender, BusinessRulesEventArgs<SalesOrderDetail> e);

            partial void OnDeleting(object sender, BusinessRulesEventArgs<SalesOrderDetail> e);
            partial void OnDeleted(object sender, BusinessRulesEventArgs<SalesOrderDetail> e);

            partial void OnGetting(object sender, BusinessRulesEventArgs<SalesOrderDetail> e);
            partial void OnTaken(object sender, BusinessRulesEventArgs<SalesOrderDetail> e);
            partial void OnCounting(object sender, BusinessRulesEventArgs<SalesOrderDetail> e);
 
 
            #endregion
			
		private static SalesOrderDetailsBR singlenton =null;
				public static SalesOrderDetailsBR NewInstance(){
					return  new SalesOrderDetailsBR();
					
				}
		public static SalesOrderDetailsBR Instance{
			get{
				if (singlenton == null)
					singlenton = new SalesOrderDetailsBR();
				return singlenton;
			}
		}
		private bool preventSecurityRestrictions = false;

		#region Fields
        EFPocoContext context = null;
        #endregion
        #region Constructor
        public SalesOrderDetailsBR()
        {
            context = new EFPocoContext();
        }
		 public SalesOrderDetailsBR(bool preventSecurity)
            {
                this.preventSecurityRestrictions = preventSecurity;
				context = new EFPocoContext();
            }
        #endregion
		
		#region Get

 		public IQueryable<SalesOrderDetail> Get()
        {
            //using (EFContext con = new EFContext())
            //{
				EFContext con = new EFContext();
                var query = con.SalesOrderDetails.AsQueryable();
                con.ContextOptions.ProxyCreationEnabled = false;

                //query = ContextQueryBuilder<Nutrient>.ApplyContextQuery(query, contextRequest);

                return query;




            //}

        }
		
		public List<SalesOrderDetail> GetAll()
        {
            return this.GetBy(p => true);
        }
        public List<SalesOrderDetail> GetAll(string includes)
        {
            return this.GetBy(p => true, includes);
        }
        public SalesOrderDetail GetByKey(Int32 salesOrderID, Int32 salesOrderDetailID)
        {
            return GetByKey(salesOrderID, salesOrderDetailID, true);
        }
        public SalesOrderDetail GetByKey(Int32 salesOrderID, Int32 salesOrderDetailID, bool loadIncludes)
        {
            SalesOrderDetail item = null;
			var query = PredicateBuilder.True<SalesOrderDetail>();
                    
			string strWhere = "SalesOrderID = " + salesOrderID.ToString()+ " And " + "SalesOrderDetailID = " + salesOrderDetailID.ToString();
            Expression<Func<SalesOrderDetail, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<SalesOrderDetail, bool>(strWhere);
			
			 ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = strWhere;

			//item = GetBy(predicate, loadIncludes, contextRequest).FirstOrDefault();
			item = GetBy(strWhere,loadIncludes,contextRequest).FirstOrDefault();
            return item;
        }
         public List<SalesOrderDetail> GetBy(string strWhere, bool loadRelations, ContextRequest contextRequest)
        {
            if (!loadRelations)
                return GetBy(strWhere, contextRequest);
            else
                return GetBy(strWhere, contextRequest, "");

        }
		  public List<SalesOrderDetail> GetBy(string strWhere, bool loadRelations)
        {
              if (!loadRelations)
                return GetBy(strWhere, new ContextRequest());
            else
                return GetBy(strWhere, new ContextRequest(), "");

        }
         public SalesOrderDetail GetByKey(Int32 salesOrderID, Int32 salesOrderDetailID, params Expression<Func<SalesOrderDetail, object>>[] includes)
        {
            SalesOrderDetail item = null;
			string strWhere = "SalesOrderID = " + salesOrderID.ToString()+ " And " + "SalesOrderDetailID = " + salesOrderDetailID.ToString();
          Expression<Func<SalesOrderDetail, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<SalesOrderDetail, bool>(strWhere);
			
        item = GetBy(predicate, includes).FirstOrDefault();
         ////   item = GetBy(strWhere,includes).FirstOrDefault();
			return item;

        }
        public SalesOrderDetail GetByKey(Int32 salesOrderID, Int32 salesOrderDetailID, string includes)
        {
            SalesOrderDetail item = null;
			string strWhere = "SalesOrderID = " + salesOrderID.ToString()+ " And " + "SalesOrderDetailID = " + salesOrderDetailID.ToString();
            
			
            item = GetBy(strWhere, includes).FirstOrDefault();
            return item;

        }

        #region Dynamic Predicate
        public List<SalesOrderDetail> GetBy(Expression<Func<SalesOrderDetail, bool>> predicate, int? pageSize, int? page)
        {
            return this.GetBy(predicate, pageSize, page, null, null);
        }
        public List<SalesOrderDetail> GetBy(Expression<Func<SalesOrderDetail, bool>> predicate, ContextRequest contextRequest)
        {

            return GetBy(predicate, contextRequest,"");
        }
        
        public List<SalesOrderDetail> GetBy(Expression<Func<SalesOrderDetail, bool>> predicate, ContextRequest contextRequest, params Expression<Func<SalesOrderDetail, object>>[] includes)
        {
            StringBuilder sb = new StringBuilder();
           if (includes != null)
            {
                foreach (var path in includes)
                {

						if (sb.Length > 0) sb.Append(",");
						sb.Append(SFSdotNet.Framework.Linq.Utils.IncludeToString<SalesOrderDetail>(path));

               }
            }
            return GetBy(predicate, contextRequest, sb.ToString());
        }
        
        
        public List<SalesOrderDetail> GetBy(Expression<Func<SalesOrderDetail, bool>> predicate, string includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";

            return GetBy(predicate, context, includes);
        }

        public List<SalesOrderDetail> GetBy(Expression<Func<SalesOrderDetail, bool>> predicate, params Expression<Func<SalesOrderDetail, object>>[] includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";
            return GetBy(predicate, context, includes);
        }

      
		public bool DisableCache { get; set; }
		 public List<SalesOrderDetail> GetBy(Expression<Func<SalesOrderDetail, bool>> predicate, ContextRequest contextRequest, string includes)
        {
            using (EFPocoContext con = new EFPocoContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;

				List<SalesOrderDetail> result = null;
                 e = null;
                OnGetting(con,e = new BusinessRulesEventArgs<SalesOrderDetail>() { FilterExpression = predicate, ContextRequest = contextRequest, FilterExpressionString = contextRequest.CustomQuery.FilterExpressionString});
				   if (e != null) {
				    predicate = e.FilterExpression;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				con.EnableChangeTrackingUsingProxies = false;
				con.WrappedContext.SalesOrderDetails.MergeOption = MergeOption.NoTracking;
                con.WrappedContext.ContextOptions.ProxyCreationEnabled = false;
                if (predicate == null) predicate = PredicateBuilder.True<SalesOrderDetail>();
 				string fkIncludes = "Product,SalesOrderHeader";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.SalesOrderDetails;
				 
                IQueryable<SalesOrderDetail> query = es.AsQueryable();

                                if (!string.IsNullOrEmpty(includes))
                {
                    foreach (string include in includes.Split(char.Parse(",")))
                    {
						if (!string.IsNullOrEmpty(include))
                            query = query.Include(include);
                    }
                }
				query =query.Where(predicate);
                query = ContextQueryBuilder<SalesOrderDetail>.ApplyContextQuery(query, contextRequest);

                result = query.ToList<SalesOrderDetail>();
				e = null;
				OnTaken(this, e = new BusinessRulesEventArgs<SalesOrderDetail>() { Items= result, FilterExpression = predicate });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
        public List<SalesOrderDetail> GetBy(string predicateString, ContextRequest contextRequest, string includes)
        {
            using (EFContext con = new EFContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;


				List<SalesOrderDetail> result = null;
                 e = null;
                  OnGetting(con,e = new BusinessRulesEventArgs<SalesOrderDetail>() {  ContextRequest = contextRequest, FilterExpressionString = predicateString });
			   	if (e != null) {
				    predicateString = e.FilterExpressionString;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				//con.EnableChangeTrackingUsingProxies = false;
				con.SalesOrderDetails.MergeOption = MergeOption.NoTracking;
                con.ContextOptions.ProxyCreationEnabled = false;
                //if (predicate == null) predicate = PredicateBuilder.True<SalesOrderDetail>();
 				string fkIncludes = "Product,SalesOrderHeader";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}else{
                    contextRequest = new ContextRequest();
                    contextRequest.CustomQuery = new CustomQuery();

                }
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.SalesOrderDetails;
				IQueryable<SalesOrderDetail> query = es.AsQueryable();

		
				// include relations FK
				if(string.IsNullOrEmpty(includes) ){
					includes ="";
				}
				bool includeProduct = includes.Split(char.Parse(",")).Contains("Product");

				bool includeSalesOrderHeader = includes.Split(char.Parse(",")).Contains("SalesOrderHeader");

				
				//string predicateString = predicate.ToDynamicLinq<SalesOrderDetail>();
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicateString, ref predicateWithManyRelations, ref predicateWithFKAndComputed);
                var _queryable = query.AsQueryable();
                if (!string.IsNullOrEmpty(predicateWithManyRelations))
                    _queryable = _queryable.Where(predicateWithManyRelations);
 
				var  queryable = _queryable.Select(                    
				p => 
                        new
                    {
					SalesOrderID = p.SalesOrderID
,SalesOrderDetailID = p.SalesOrderDetailID
,OrderQty = p.OrderQty
,UnitPrice = p.UnitPrice
,UnitPriceDiscount = p.UnitPriceDiscount
,LineTotal = p.LineTotal
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

,Product = includeProduct ? p.Product:null
,SalesOrderHeader = includeSalesOrderHeader ? p.SalesOrderHeader:null


	
                    }
                    
                    );
					
				
                    if (!string.IsNullOrEmpty(predicateWithFKAndComputed))
                        queryable = queryable.Where(predicateWithFKAndComputed, contextRequest.CustomQuery.ExtraParams);

				QueryComplementOptions queryOps = ContextQueryBuilder.ApplyContextQuery(contextRequest);
            	if (!string.IsNullOrEmpty(queryOps.OrderByAndSort))
					queryable = queryable.OrderBy(queryOps.OrderByAndSort);
               	if (queryOps.Skip != null)
                {
                    queryable = queryable.Skip(queryOps.Skip.Value);
                }
                if (queryOps.PageSize != null)
                {
                    queryable = queryable.Take (queryOps.PageSize.Value);
                }
                result = queryable.AsEnumerable().
                    Select(
                    p =>  new SalesOrderDetail()
                    {
					SalesOrderID = p.SalesOrderID
,SalesOrderDetailID = p.SalesOrderDetailID
,OrderQty = p.OrderQty
,UnitPrice = p.UnitPrice
,UnitPriceDiscount = p.UnitPriceDiscount
,LineTotal = p.LineTotal
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate
,Product = p.Product
,SalesOrderHeader = p.SalesOrderHeader

                    }
                     ).ToList();

				e = null;
			OnTaken(this, e = new BusinessRulesEventArgs<SalesOrderDetail>() { Items= result, FilterExpressionString  = predicateString });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
		public List<SalesOrderDetail> GetBy(Expression<Func<SalesOrderDetail, bool>> predicate, bool loadRelations, ContextRequest contextRequest)
        {
			if(!loadRelations)
				return GetBy(predicate, contextRequest);
			else
				return GetBy(predicate, contextRequest, "");

        }

        public List<SalesOrderDetail> GetBy(Expression<Func<SalesOrderDetail, bool>> predicate, int? pageSize, int? page, string orderBy, SFSdotNet.Framework.Data.SortDirection? sortDirection)
        {
            return GetBy(predicate, new ContextRequest() { CustomQuery = new CustomQuery() { Page = page, PageSize = pageSize, OrderBy = orderBy, SortDirection = sortDirection } });
        }
        public List<SalesOrderDetail> GetBy(Expression<Func<SalesOrderDetail, bool>> predicate)
        {
		
			ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = null;
            return this.GetBy(predicate, contextRequest, "");
        }
        #endregion
        #region Dynamic String
		private string GetSpecificFilter(string filter) {
            string result = "";
		    string linqFilter = String.Empty;
            string freeTextFilter = String.Empty;
            if (filter.Contains("|"))
            {
                linqFilter = filter.Split(char.Parse("|"))[0];
                freeTextFilter = filter.Split(char.Parse("|"))[1];
            }
 			else {
                linqFilter = filter;
            }
            string specificFilter = linqFilter;
            if (!string.IsNullOrEmpty(freeTextFilter))
            {
                System.Text.StringBuilder sbCont = new System.Text.StringBuilder();
                if (specificFilter.Length > 0)
                {
                    sbCont.Append(" AND ");
                    sbCont.Append(" ({0})");
                }
                else
                {
                    sbCont.Append("{0}");
                }
                var words = freeTextFilter.Split(char.Parse(" "));
                System.Text.StringBuilder sbSpec = new System.Text.StringBuilder();
                 int nWords = 1;
				foreach (var word in words)
                {
                    if (sbSpec.Length > 0) sbSpec.Append(" AND ");
                    sbSpec.Append("(");
					
	
					
	
					
	
					
	
					
	
					
	
					
	
					
	
					
	
					
	
					
			
                    sbSpec.Append(")");
					
					nWords++;

                }
                specificFilter = string.Format("{0}{1}", specificFilter, string.Format(sbCont.ToString(), sbSpec.ToString()));
            }
			result = specificFilter;
			
			return result;

		}
		public List<SalesOrderDetail> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params object[] extraParams)
        {
        	string specificFilter = "";
            if (!string.IsNullOrEmpty(filter))
              specificFilter=  GetSpecificFilter(filter);
            if (string.IsNullOrEmpty(orderBy))
            {
			                orderBy = "SalesOrderID";
            }
			SFSdotNet.Framework.Data.SortDirection direction = SFSdotNet.Framework.Data.SortDirection.Ascending;
            if (!string.IsNullOrEmpty(orderDir))
            {
                if (orderDir == "desc")
                    direction = SFSdotNet.Framework.Data.SortDirection.Descending;
            }
            return BR.SalesOrderDetailsBR.Instance.GetBy(specificFilter,
                new SFSdotNet.Framework.My.ContextRequest()
                {
                    CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
                    {
						ExtraParams= extraParams,
               
                        OrderBy = orderBy,
                        SortDirection = direction,
                        Page = page,
                        PageSize = pageSize
                    }
                });
        }


        public List<SalesOrderDetail> GetBy(string strWhere, ContextRequest contextRequest)
        {
        	#region old code
				Expression<Func<SalesOrderDetail, bool>> predicate = null;
                if (!string.IsNullOrEmpty(strWhere)){

                    object[] extraParams = null;
                    if (contextRequest != null )
                        if (contextRequest.CustomQuery != null )
                            extraParams = contextRequest.CustomQuery.ExtraParams;
                    predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<SalesOrderDetail, bool>(strWhere, extraParams);				}
				 if (contextRequest == null)
                {
                    contextRequest = new ContextRequest();
                    if (contextRequest.CustomQuery == null)
                        contextRequest.CustomQuery = new CustomQuery();
                }
                
            contextRequest.CustomQuery.FilterExpressionString = strWhere;
				//return GetBy(predicate, contextRequest);  

			#endregion				
				
                    return GetBy(strWhere, contextRequest, "");  


        }
       public List<SalesOrderDetail> GetBy(string strWhere)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
			
            return GetBy(strWhere, context, null);
        }

        public List<SalesOrderDetail> GetBy(string strWhere, string includes)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
            return GetBy(strWhere, context, includes);
        }

        #endregion
        #endregion
		
		  #region SaveOrUpdate
        private SalesOrderDetail Save(SalesOrderDetail entity, bool saveChanges, EFPocoContext con)
        {
				ObjectContext context = null;
            return Update(entity, saveChanges, out context);

			
        }

 		 public SalesOrderDetail Create(SalesOrderDetail entity)
        {
				ObjectContext context = null;
				return this.Create(entity, true, out context);

        }
         public SalesOrderDetail Create(SalesOrderDetail entity, bool saveChanges, out ObjectContext context)
        {
                    return Create(entity, saveChanges , out context, null);
        }
         public SalesOrderDetail Create(SalesOrderDetail entity, params Expression<Func<SalesOrderDetail,object>>[] paths)
        {
            ObjectContext context = null;
            if(paths != null)
				return Create(entity, true, out context, paths);
			else 
				return Create(entity, true, out context);
        }
        public SalesOrderDetail Create(SalesOrderDetail entity, bool saveChanges, out ObjectContext context, params Expression<Func<SalesOrderDetail,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				SalesOrderDetail itemResult = null;
#region Autos
	

			entity.rowguid = Guid.NewGuid();
	
	

#endregion
                e = null;
                OnCreating(this,e = new BusinessRulesEventArgs<SalesOrderDetail>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							context = null;
							return e.Item;

						}
					}



				SalesOrderDetailAdapter adapter = con.GetAdapterObject<SalesOrderDetailAdapter>(entity);;
				List<Expression<Func<SalesOrderDetailAdapter, object>>> paths = new List<Expression<Func<SalesOrderDetailAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(SalesOrderDetailAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<SalesOrderDetailAdapter, object>> path  = null;
                        switch(member.Member.Name){
							
							default:
								path = p => member;
							break;
                        }

                        
                       paths.Add(path.Expand());
                    }
                }
                object aux = null;
					paths.Add(p => p.Product.WithoutUpdate());

					paths.Add(p => p.SalesOrderHeader.WithoutUpdate());

					//paths = pathBuilder.ToArray();

				if (adapter.Product != null ){
					if(adapter.Product.EntityKey == null) adapter.Product.EntityKey = con.WrappedContext.CreateEntityKey("Products", adapter.Product);
				}
				if (adapter.SalesOrderHeader != null ){
					if(adapter.SalesOrderHeader.EntityKey == null) adapter.SalesOrderHeader.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderHeaders", adapter.SalesOrderHeader);
				}



                //con.WrappedContext.AttachObjectGraph<SalesOrderDetailAdapter>(adapter, p=>p.Product, p=>p.SalesOrderHeader);
                con.WrappedContext.AttachObjectGraph<SalesOrderDetailAdapter>(adapter, paths.ToArray());
              	if (saveChanges){
                    con.WrappedContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
					 
				}
                else
                    con.WrappedContext.SaveChanges(SaveOptions.None);
                if (!saveChanges)
                    context = con.WrappedContext;
                else
                    context = null;
				itemResult = adapter.PocoEntity;
                OnCreated(this, e = new BusinessRulesEventArgs<SalesOrderDetail>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });
                return itemResult;
            }
        }
        BusinessRulesEventArgs<SalesOrderDetail> e = null;
        public void Create(List<SalesOrderDetail> entities)
        {
				ObjectContext context = null;
				foreach (SalesOrderDetail entity in entities)
				{
					this.Create(entity, true, out context);
				}

				
				
        }

        public SalesOrderDetail Update(SalesOrderDetail entity)
        {
			ObjectContext context = null;
            return Update(entity, true, out context, null);

        }
         public SalesOrderDetail Update(SalesOrderDetail entity, params Expression<Func<SalesOrderDetail, object>>[] paths)
        {
			  ObjectContext context = null;
            return Update(entity, true, out context, paths);
         }
        public SalesOrderDetail Update(SalesOrderDetail entity, bool saveChanges, out ObjectContext outcontext)
        {
			return Update(entity, saveChanges, out outcontext, null);
		}
         public SalesOrderDetail Update(SalesOrderDetail entity, bool saveChanges, out ObjectContext outcontext, params Expression<Func<SalesOrderDetail,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				SalesOrderDetail  itemResult = null;

	

				e = null;
                OnUpdating(this,e = new BusinessRulesEventArgs<SalesOrderDetail>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							outcontext = null;
							return e.Item;

						}
					}

                SalesOrderDetailAdapter adapter = con.GetAdapterObject<SalesOrderDetailAdapter>(entity);
                adapter.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderDetails", adapter);
				    var es = con.SalesOrderDetails;
				List<Expression<Func<SalesOrderDetailAdapter, object>>> paths = new List<Expression<Func<SalesOrderDetailAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(SalesOrderDetailAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<SalesOrderDetailAdapter, object>> path  = null;
                        switch(member.Member.Name){
							
							default:
								path = p => member;
							break;
                        }

                        paths.Add(path.Expand());
 					}
                }
                else {
                  paths = new List<Expression<Func<SalesOrderDetailAdapter, object>>>();

					//List<Expression<Func<SalesOrderDetailAdapter,object>>> pathBuilder = new List<Expression<Func<SalesOrderDetailAdapter,object>>>();
					paths.Add(p => p.Product.WithoutUpdate());

					paths.Add(p => p.SalesOrderHeader.WithoutUpdate());

		
					//paths = pathBuilder.ToArray();		
			}
			object aux = null;
				if (adapter.Product != null ){
					if(adapter.Product.EntityKey == null) adapter.Product.EntityKey = con.WrappedContext.CreateEntityKey("Products", adapter.Product);
				}

                
				if (adapter.SalesOrderHeader != null ){
					if(adapter.SalesOrderHeader.EntityKey == null) adapter.SalesOrderHeader.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderHeaders", adapter.SalesOrderHeader);
				}

                



                //con.AttachObjectGraph<SalesOrderDetail>(adapter, p=>p.Product, p=>p.SalesOrderHeader);
                con.WrappedContext.AttachObjectGraph<SalesOrderDetailAdapter>(adapter, paths.ToArray());
				if (saveChanges){
                	con.WrappedContext.SaveChanges();
					 
					}
                if(!saveChanges)
					outcontext = con.WrappedContext;
				else
					outcontext = null;
				itemResult = adapter.PocoEntity;
				OnUpdated(this, e = new BusinessRulesEventArgs<SalesOrderDetail>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });

              	return itemResult;

			  }
        }
        public SalesOrderDetail Save(SalesOrderDetail entity)
        {
			return Save(entity, true, null);
        }
        public int Save(List<SalesOrderDetail> entities)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
			
            int n = 0;
            foreach (SalesOrderDetail item in entities)
            {
                try
                {
                    this.Save(item, false, con);
                    n++;
                }catch (Exception ex){
                    SFSdotNet.Framework.My.EventLog.Exception(ex);
                }
            }
            con.SaveChanges();
            return n;
            }
        }
        #endregion
        #region Delete
        public void Delete(SalesOrderDetail entity)
        {
				ObjectContext context = null;
				this.Delete(entity, true, out context);
			
        }

        
        public void Delete(SalesOrderDetail entity, bool saveChanges, out  ObjectContext context)
        {
			using (EFPocoContext _con = new EFPocoContext())
			{
				int result = 0;
				
               	BusinessRulesEventArgs<SalesOrderDetail> _e = null;
                OnDeleting(this,_e = new BusinessRulesEventArgs<SalesOrderDetail>() { Item=entity, SaveChanges =saveChanges });
				   if (_e != null) {
						if (_e.Cancel)
						{
							context = null;
							return;

						}
					}


				SalesOrderDetailAdapter adapter = _con.GetAdapterObject<SalesOrderDetailAdapter>(entity);
                adapter.EntityKey = _con.WrappedContext.CreateEntityKey("SalesOrderDetails", adapter);
                
	            //adapter = _con.WrappedContext.AttachObjectGraph<SalesOrderDetailAdapter>(adapter);
				_con.WrappedContext.AttachTo("SalesOrderDetails", adapter);
                
									_con.WrappedContext.DeleteObject(adapter);
                				
				if (!saveChanges)
                    context = _con.WrappedContext;
                else
                    context = null;
				 SaveOptions saveOption = SaveOptions.None;
                if (saveChanges)
                    saveOption = SaveOptions.AcceptAllChangesAfterSave;

				result = _con.WrappedContext.SaveChanges(saveOption);
				if (saveChanges){
					
					}
				if (_e == null)
					_e = new BusinessRulesEventArgs<SalesOrderDetail>() { Item = entity };
                OnDeleted(this, _e );

				//return null;
			}            
        }
        public void Delete(List<SalesOrderDetail> entities)
        {
				ObjectContext context = null;
			
				foreach (SalesOrderDetail item in entities)
				{
					this.Delete(item, true, out context);
				}
			

			
        }
        #endregion
 
        #region GetCount
        public int GetCount(Expression<Func<SalesOrderDetail, bool>> predicate)
        {
		
			using (EFPocoContext con = new EFPocoContext())
			{


				if (predicate == null) predicate = PredicateBuilder.True<SalesOrderDetail>();
				
				return con.SalesOrderDetails.Count(predicate);
			}

        }
        public int GetCount(string predicate)
        {
			e = null;
            OnCounting(this, e = new BusinessRulesEventArgs<SalesOrderDetail>() {  FilterExpressionString = predicate });
            if (e != null)
            {
                if (e.Cancel)
                {
                    context = null;
                    return e.CountResult;

                }
                predicate = e.FilterExpressionString;
            
            }
					predicate = GetSpecificFilter(predicate);
			using (EFContext con = new EFContext())
			{
				   
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicate, ref predicateWithManyRelations, ref predicateWithFKAndComputed);

                if (!string.IsNullOrEmpty(predicate))
                {
				
					
                    return con.SalesOrderDetails.Count(System.Linq.Dynamic.DynamicExpression.ParseLambda<SalesOrderDetail, bool>(predicate));
					
                }else
                    return con.SalesOrderDetails.Count();

			}

		}
         public int GetCount()
        {
            return GetCount(p => true);
        }
        #endregion
        
         public SalesOrderDetail Update(SalesOrderDetail entity, string paths)
        {
            return Update(entity, paths.Split(char.Parse(",")));
            
        }

        public SalesOrderDetail Update(SalesOrderDetail entity, string[] paths)
        {
            // Translate
            List<Expression<Func<SalesOrderDetail, object>>> pathList = new List<Expression<Func<SalesOrderDetail, object>>>();
            for (int i = 0; i <= paths.Length -1; i++)
            {
                var param = Expression.Parameter(typeof(SalesOrderDetail), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<SalesOrderDetail, object>> path = p => member;
                pathList.Add(path.Expand());
            }
           return Update(entity, pathList.ToArray());
        }

        public void Update(List<SalesOrderDetail> entities, string paths)
        {
            foreach (var entity in entities )
            {
                Update(entity, paths);
            }
        }

        public SalesOrderDetail Create(SalesOrderDetail entity, string paths)
        {
			if(string.IsNullOrEmpty(paths))
				return Create(entity);
				
            return Create(entity, paths.Split(char.Parse(",")));
        }

        public  void Create(List<SalesOrderDetail> entities, string paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }

        public void Create(List<SalesOrderDetail> entities, string[] paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }
        
        public SalesOrderDetail  Create(SalesOrderDetail entity, string[] paths)
        {
            List<Expression<Func<SalesOrderDetail, object>>> pathList = new List<Expression<Func<SalesOrderDetail, object>>>();
            for (int i = 0; i < paths.Length - 1; i++)
            {
                var param = Expression.Parameter(typeof(SalesOrderDetail), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<SalesOrderDetail, object>> path = p => member;
                pathList.Add(path.Expand());
            }
            return Create(entity, pathList.ToArray());
        }
        public void Delete(List<SalesOrderDetail.CompositeKey> entityKeys)
        {

            List<SalesOrderDetail> items = new List<SalesOrderDetail>();
            foreach (var itemKey in entityKeys)
            {
                items.Add(GetByKey(itemKey.SalesOrderID, itemKey.SalesOrderDetailID));
            }

            Delete(items);

        }
		
		
	}
		public partial class SalesOrderHeadersBR{
	 	
           
		 #region Partial methods

           partial void OnUpdating(object sender, BusinessRulesEventArgs<SalesOrderHeader> e);

            partial void OnUpdated(object sender, BusinessRulesEventArgs<SalesOrderHeader> e);

            partial void OnCreating(object sender, BusinessRulesEventArgs<SalesOrderHeader> e);
            partial void OnCreated(object sender, BusinessRulesEventArgs<SalesOrderHeader> e);

            partial void OnDeleting(object sender, BusinessRulesEventArgs<SalesOrderHeader> e);
            partial void OnDeleted(object sender, BusinessRulesEventArgs<SalesOrderHeader> e);

            partial void OnGetting(object sender, BusinessRulesEventArgs<SalesOrderHeader> e);
            partial void OnTaken(object sender, BusinessRulesEventArgs<SalesOrderHeader> e);
            partial void OnCounting(object sender, BusinessRulesEventArgs<SalesOrderHeader> e);
 
 
            #endregion
			
		private static SalesOrderHeadersBR singlenton =null;
				public static SalesOrderHeadersBR NewInstance(){
					return  new SalesOrderHeadersBR();
					
				}
		public static SalesOrderHeadersBR Instance{
			get{
				if (singlenton == null)
					singlenton = new SalesOrderHeadersBR();
				return singlenton;
			}
		}
		private bool preventSecurityRestrictions = false;

		#region Fields
        EFPocoContext context = null;
        #endregion
        #region Constructor
        public SalesOrderHeadersBR()
        {
            context = new EFPocoContext();
        }
		 public SalesOrderHeadersBR(bool preventSecurity)
            {
                this.preventSecurityRestrictions = preventSecurity;
				context = new EFPocoContext();
            }
        #endregion
		
		#region Get

 		public IQueryable<SalesOrderHeader> Get()
        {
            //using (EFContext con = new EFContext())
            //{
				EFContext con = new EFContext();
                var query = con.SalesOrderHeaders.AsQueryable();
                con.ContextOptions.ProxyCreationEnabled = false;

                //query = ContextQueryBuilder<Nutrient>.ApplyContextQuery(query, contextRequest);

                return query;




            //}

        }
		
		public List<SalesOrderHeader> GetAll()
        {
            return this.GetBy(p => true);
        }
        public List<SalesOrderHeader> GetAll(string includes)
        {
            return this.GetBy(p => true, includes);
        }
        public SalesOrderHeader GetByKey(Int32 salesOrderID)
        {
            return GetByKey(salesOrderID, true);
        }
        public SalesOrderHeader GetByKey(Int32 salesOrderID, bool loadIncludes)
        {
            SalesOrderHeader item = null;
			var query = PredicateBuilder.True<SalesOrderHeader>();
                    
			string strWhere = "SalesOrderID = " + salesOrderID.ToString();
            Expression<Func<SalesOrderHeader, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<SalesOrderHeader, bool>(strWhere);
			
			 ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = strWhere;

			//item = GetBy(predicate, loadIncludes, contextRequest).FirstOrDefault();
			item = GetBy(strWhere,loadIncludes,contextRequest).FirstOrDefault();
            return item;
        }
         public List<SalesOrderHeader> GetBy(string strWhere, bool loadRelations, ContextRequest contextRequest)
        {
            if (!loadRelations)
                return GetBy(strWhere, contextRequest);
            else
                return GetBy(strWhere, contextRequest, "");

        }
		  public List<SalesOrderHeader> GetBy(string strWhere, bool loadRelations)
        {
              if (!loadRelations)
                return GetBy(strWhere, new ContextRequest());
            else
                return GetBy(strWhere, new ContextRequest(), "");

        }
         public SalesOrderHeader GetByKey(Int32 salesOrderID, params Expression<Func<SalesOrderHeader, object>>[] includes)
        {
            SalesOrderHeader item = null;
			string strWhere = "SalesOrderID = " + salesOrderID.ToString();
          Expression<Func<SalesOrderHeader, bool>> predicate = null;
            if (!string.IsNullOrEmpty(strWhere))
                predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<SalesOrderHeader, bool>(strWhere);
			
        item = GetBy(predicate, includes).FirstOrDefault();
         ////   item = GetBy(strWhere,includes).FirstOrDefault();
			return item;

        }
        public SalesOrderHeader GetByKey(Int32 salesOrderID, string includes)
        {
            SalesOrderHeader item = null;
			string strWhere = "SalesOrderID = " + salesOrderID.ToString();
            
			
            item = GetBy(strWhere, includes).FirstOrDefault();
            return item;

        }

        #region Dynamic Predicate
        public List<SalesOrderHeader> GetBy(Expression<Func<SalesOrderHeader, bool>> predicate, int? pageSize, int? page)
        {
            return this.GetBy(predicate, pageSize, page, null, null);
        }
        public List<SalesOrderHeader> GetBy(Expression<Func<SalesOrderHeader, bool>> predicate, ContextRequest contextRequest)
        {

            return GetBy(predicate, contextRequest,"");
        }
        
        public List<SalesOrderHeader> GetBy(Expression<Func<SalesOrderHeader, bool>> predicate, ContextRequest contextRequest, params Expression<Func<SalesOrderHeader, object>>[] includes)
        {
            StringBuilder sb = new StringBuilder();
           if (includes != null)
            {
                foreach (var path in includes)
                {

						if (sb.Length > 0) sb.Append(",");
						sb.Append(SFSdotNet.Framework.Linq.Utils.IncludeToString<SalesOrderHeader>(path));

               }
            }
            return GetBy(predicate, contextRequest, sb.ToString());
        }
        
        
        public List<SalesOrderHeader> GetBy(Expression<Func<SalesOrderHeader, bool>> predicate, string includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";

            return GetBy(predicate, context, includes);
        }

        public List<SalesOrderHeader> GetBy(Expression<Func<SalesOrderHeader, bool>> predicate, params Expression<Func<SalesOrderHeader, object>>[] includes)
        {
			ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = "";
            return GetBy(predicate, context, includes);
        }

      
		public bool DisableCache { get; set; }
		 public List<SalesOrderHeader> GetBy(Expression<Func<SalesOrderHeader, bool>> predicate, ContextRequest contextRequest, string includes)
        {
            using (EFPocoContext con = new EFPocoContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;

				List<SalesOrderHeader> result = null;
                 e = null;
                OnGetting(con,e = new BusinessRulesEventArgs<SalesOrderHeader>() { FilterExpression = predicate, ContextRequest = contextRequest, FilterExpressionString = contextRequest.CustomQuery.FilterExpressionString});
				   if (e != null) {
				    predicate = e.FilterExpression;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				con.EnableChangeTrackingUsingProxies = false;
				con.WrappedContext.SalesOrderHeaders.MergeOption = MergeOption.NoTracking;
                con.WrappedContext.ContextOptions.ProxyCreationEnabled = false;
                if (predicate == null) predicate = PredicateBuilder.True<SalesOrderHeader>();
 				string fkIncludes = "Address,Address1,Customer";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.SalesOrderHeaders;
				 
                IQueryable<SalesOrderHeader> query = es.AsQueryable();

                                if (!string.IsNullOrEmpty(includes))
                {
                    foreach (string include in includes.Split(char.Parse(",")))
                    {
						if (!string.IsNullOrEmpty(include))
                            query = query.Include(include);
                    }
                }
				query =query.Where(predicate);
                query = ContextQueryBuilder<SalesOrderHeader>.ApplyContextQuery(query, contextRequest);

                result = query.ToList<SalesOrderHeader>();
				e = null;
				OnTaken(this, e = new BusinessRulesEventArgs<SalesOrderHeader>() { Items= result, FilterExpression = predicate });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
        public List<SalesOrderHeader> GetBy(string predicateString, ContextRequest contextRequest, string includes)
        {
            using (EFContext con = new EFContext())
            {
				if (DisableCache) 
                	con.CachingPolicy = EFCachingProvider.Caching.CachingPolicy.NoCaching;


				List<SalesOrderHeader> result = null;
                 e = null;
                  OnGetting(con,e = new BusinessRulesEventArgs<SalesOrderHeader>() {  ContextRequest = contextRequest, FilterExpressionString = predicateString });
			   	if (e != null) {
				    predicateString = e.FilterExpressionString;
						if (e.Cancel)
						{
							context = null;
							return e.Items;

						}
						if (!string.IsNullOrEmpty(e.StringIncludes))
                            includes = e.StringIncludes;
					}
				//con.EnableChangeTrackingUsingProxies = false;
				con.SalesOrderHeaders.MergeOption = MergeOption.NoTracking;
                con.ContextOptions.ProxyCreationEnabled = false;
                //if (predicate == null) predicate = PredicateBuilder.True<SalesOrderHeader>();
 				string fkIncludes = "Address,Address1,Customer";
                if(contextRequest!=null){
					if (contextRequest.CustomQuery != null)
					{
						if (contextRequest.CustomQuery.IncludeForeignKeyPaths != null) {
							if (contextRequest.CustomQuery.IncludeForeignKeyPaths.Value == false)
								fkIncludes = "";
						}
					}
				}else{
                    contextRequest = new ContextRequest();
                    contextRequest.CustomQuery = new CustomQuery();

                }
				if (!string.IsNullOrEmpty(includes))
					includes = includes + "," + fkIncludes;
				else
					includes = fkIncludes;
                
                var es = con.SalesOrderHeaders;
				IQueryable<SalesOrderHeader> query = es.AsQueryable();

		
				// include relations FK
				if(string.IsNullOrEmpty(includes) ){
					includes ="";
				}
				bool includeAddress = includes.Split(char.Parse(",")).Contains("Address");

				bool includeAddress1 = includes.Split(char.Parse(",")).Contains("Address1");

				bool includeCustomer = includes.Split(char.Parse(",")).Contains("Customer");

				
				//string predicateString = predicate.ToDynamicLinq<SalesOrderHeader>();
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicateString, ref predicateWithManyRelations, ref predicateWithFKAndComputed);
                var _queryable = query.AsQueryable();
                if (!string.IsNullOrEmpty(predicateWithManyRelations))
                    _queryable = _queryable.Where(predicateWithManyRelations);
 
				var  queryable = _queryable.Select(                    
				p => 
                        new
                    {
					SalesOrderID = p.SalesOrderID
,RevisionNumber = p.RevisionNumber
,OrderDate = p.OrderDate
,DueDate = p.DueDate
,ShipDate = p.ShipDate
,Status = p.Status
,OnlineOrderFlag = p.OnlineOrderFlag
,SalesOrderNumber = p.SalesOrderNumber
,PurchaseOrderNumber = p.PurchaseOrderNumber
,AccountNumber = p.AccountNumber
,ShipMethod = p.ShipMethod
,CreditCardApprovalCode = p.CreditCardApprovalCode
,SubTotal = p.SubTotal
,TaxAmt = p.TaxAmt
,Freight = p.Freight
,TotalDue = p.TotalDue
,Comment = p.Comment
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate

,Address = includeAddress ? p.Address:null
,Address1 = includeAddress1 ? p.Address1:null
,Customer = includeCustomer ? p.Customer:null


	
                    }
                    
                    );
					
				
                    if (!string.IsNullOrEmpty(predicateWithFKAndComputed))
                        queryable = queryable.Where(predicateWithFKAndComputed, contextRequest.CustomQuery.ExtraParams);

				QueryComplementOptions queryOps = ContextQueryBuilder.ApplyContextQuery(contextRequest);
            	if (!string.IsNullOrEmpty(queryOps.OrderByAndSort))
					queryable = queryable.OrderBy(queryOps.OrderByAndSort);
               	if (queryOps.Skip != null)
                {
                    queryable = queryable.Skip(queryOps.Skip.Value);
                }
                if (queryOps.PageSize != null)
                {
                    queryable = queryable.Take (queryOps.PageSize.Value);
                }
                result = queryable.AsEnumerable().
                    Select(
                    p =>  new SalesOrderHeader()
                    {
					SalesOrderID = p.SalesOrderID
,RevisionNumber = p.RevisionNumber
,OrderDate = p.OrderDate
,DueDate = p.DueDate
,ShipDate = p.ShipDate
,Status = p.Status
,OnlineOrderFlag = p.OnlineOrderFlag
,SalesOrderNumber = p.SalesOrderNumber
,PurchaseOrderNumber = p.PurchaseOrderNumber
,AccountNumber = p.AccountNumber
,ShipMethod = p.ShipMethod
,CreditCardApprovalCode = p.CreditCardApprovalCode
,SubTotal = p.SubTotal
,TaxAmt = p.TaxAmt
,Freight = p.Freight
,TotalDue = p.TotalDue
,Comment = p.Comment
,rowguid = p.rowguid
,ModifiedDate = p.ModifiedDate
,Address = p.Address
,Address1 = p.Address1
,Customer = p.Customer

                    }
                     ).ToList();

				e = null;
			OnTaken(this, e = new BusinessRulesEventArgs<SalesOrderHeader>() { Items= result, FilterExpressionString  = predicateString });
  
                if (e != null) {
                    if (e.ReplaceResult)
                        result = e.Items;
                }
                return result;
            }
        }
		public List<SalesOrderHeader> GetBy(Expression<Func<SalesOrderHeader, bool>> predicate, bool loadRelations, ContextRequest contextRequest)
        {
			if(!loadRelations)
				return GetBy(predicate, contextRequest);
			else
				return GetBy(predicate, contextRequest, "SalesOrderDetails");

        }

        public List<SalesOrderHeader> GetBy(Expression<Func<SalesOrderHeader, bool>> predicate, int? pageSize, int? page, string orderBy, SFSdotNet.Framework.Data.SortDirection? sortDirection)
        {
            return GetBy(predicate, new ContextRequest() { CustomQuery = new CustomQuery() { Page = page, PageSize = pageSize, OrderBy = orderBy, SortDirection = sortDirection } });
        }
        public List<SalesOrderHeader> GetBy(Expression<Func<SalesOrderHeader, bool>> predicate)
        {
		
			ContextRequest contextRequest = new ContextRequest();
            contextRequest.CustomQuery = new CustomQuery();
            contextRequest.CustomQuery.FilterExpressionString = null;
            return this.GetBy(predicate, contextRequest, "");
        }
        #endregion
        #region Dynamic String
		private string GetSpecificFilter(string filter) {
            string result = "";
		    string linqFilter = String.Empty;
            string freeTextFilter = String.Empty;
            if (filter.Contains("|"))
            {
                linqFilter = filter.Split(char.Parse("|"))[0];
                freeTextFilter = filter.Split(char.Parse("|"))[1];
            }
 			else {
                linqFilter = filter;
            }
            string specificFilter = linqFilter;
            if (!string.IsNullOrEmpty(freeTextFilter))
            {
                System.Text.StringBuilder sbCont = new System.Text.StringBuilder();
                if (specificFilter.Length > 0)
                {
                    sbCont.Append(" AND ");
                    sbCont.Append(" ({0})");
                }
                else
                {
                    sbCont.Append("{0}");
                }
                var words = freeTextFilter.Split(char.Parse(" "));
                System.Text.StringBuilder sbSpec = new System.Text.StringBuilder();
                 int nWords = 1;
				foreach (var word in words)
                {
                    if (sbSpec.Length > 0) sbSpec.Append(" AND ");
                    sbSpec.Append("(");
					
	
					
	
					
	
					
	
					
	
					
	
					
	
					
											
					sbSpec.Append(string.Format(@"SalesOrderNumber.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"PurchaseOrderNumber.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"AccountNumber.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"ShipMethod.Contains(""{0}"")", word));

					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"CreditCardApprovalCode.Contains(""{0}"")", word));

					
	
					
	
					
	
					
	
					
											sbSpec.Append(" OR ");
										
					sbSpec.Append(string.Format(@"Comment.Contains(""{0}"")", word));

					
	
					
	
					
	
					
	
					
	
					
			
                    sbSpec.Append(")");
					
					nWords++;

                }
                specificFilter = string.Format("{0}{1}", specificFilter, string.Format(sbCont.ToString(), sbSpec.ToString()));
            }
			result = specificFilter;
			
			return result;

		}
		public List<SalesOrderHeader> GetBy(string filter, int? pageSize, int? page, string orderBy, string orderDir,  params object[] extraParams)
        {
        	string specificFilter = "";
            if (!string.IsNullOrEmpty(filter))
              specificFilter=  GetSpecificFilter(filter);
            if (string.IsNullOrEmpty(orderBy))
            {
			                orderBy = "SalesOrderNumber";
            }
			SFSdotNet.Framework.Data.SortDirection direction = SFSdotNet.Framework.Data.SortDirection.Ascending;
            if (!string.IsNullOrEmpty(orderDir))
            {
                if (orderDir == "desc")
                    direction = SFSdotNet.Framework.Data.SortDirection.Descending;
            }
            return BR.SalesOrderHeadersBR.Instance.GetBy(specificFilter,
                new SFSdotNet.Framework.My.ContextRequest()
                {
                    CustomQuery = new SFSdotNet.Framework.My.CustomQuery()
                    {
						ExtraParams= extraParams,
               
                        OrderBy = orderBy,
                        SortDirection = direction,
                        Page = page,
                        PageSize = pageSize
                    }
                });
        }


        public List<SalesOrderHeader> GetBy(string strWhere, ContextRequest contextRequest)
        {
        	#region old code
				Expression<Func<SalesOrderHeader, bool>> predicate = null;
                if (!string.IsNullOrEmpty(strWhere)){

                    object[] extraParams = null;
                    if (contextRequest != null )
                        if (contextRequest.CustomQuery != null )
                            extraParams = contextRequest.CustomQuery.ExtraParams;
                    predicate = System.Linq.Dynamic.DynamicExpression.ParseLambda<SalesOrderHeader, bool>(strWhere, extraParams);				}
				 if (contextRequest == null)
                {
                    contextRequest = new ContextRequest();
                    if (contextRequest.CustomQuery == null)
                        contextRequest.CustomQuery = new CustomQuery();
                }
                
            contextRequest.CustomQuery.FilterExpressionString = strWhere;
				//return GetBy(predicate, contextRequest);  

			#endregion				
				
                    return GetBy(strWhere, contextRequest, "");  


        }
       public List<SalesOrderHeader> GetBy(string strWhere)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
			
            return GetBy(strWhere, context, null);
        }

        public List<SalesOrderHeader> GetBy(string strWhere, string includes)
        {
		 	ContextRequest context = new ContextRequest();
            context.CustomQuery = new CustomQuery();
            context.CustomQuery.FilterExpressionString = strWhere;
            return GetBy(strWhere, context, includes);
        }

        #endregion
        #endregion
		
		  #region SaveOrUpdate
        private SalesOrderHeader Save(SalesOrderHeader entity, bool saveChanges, EFPocoContext con)
        {
				ObjectContext context = null;
            return Update(entity, saveChanges, out context);

			
        }

 		 public SalesOrderHeader Create(SalesOrderHeader entity)
        {
				ObjectContext context = null;
				return this.Create(entity, true, out context);

        }
         public SalesOrderHeader Create(SalesOrderHeader entity, bool saveChanges, out ObjectContext context)
        {
                    return Create(entity, saveChanges , out context, null);
        }
         public SalesOrderHeader Create(SalesOrderHeader entity, params Expression<Func<SalesOrderHeader,object>>[] paths)
        {
            ObjectContext context = null;
            if(paths != null)
				return Create(entity, true, out context, paths);
			else 
				return Create(entity, true, out context);
        }
        public SalesOrderHeader Create(SalesOrderHeader entity, bool saveChanges, out ObjectContext context, params Expression<Func<SalesOrderHeader,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				SalesOrderHeader itemResult = null;
#region Autos
	

			entity.rowguid = Guid.NewGuid();
	
	

#endregion
                e = null;
                OnCreating(this,e = new BusinessRulesEventArgs<SalesOrderHeader>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							context = null;
							return e.Item;

						}
					}



				SalesOrderHeaderAdapter adapter = con.GetAdapterObject<SalesOrderHeaderAdapter>(entity);;
				List<Expression<Func<SalesOrderHeaderAdapter, object>>> paths = new List<Expression<Func<SalesOrderHeaderAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(SalesOrderHeaderAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<SalesOrderHeaderAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "SalesOrderDetails":
								path = p => p.SalesOrderDetails.First().WithoutUpdate();

								//path = p => member;
								//path = p => p.SalesOrderDetails.First().Product.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        
                       paths.Add(path.Expand());
                    }
                }
                object aux = null;
					paths.Add(p => p.Address.WithoutUpdate());

					paths.Add(p => p.Address1.WithoutUpdate());

					paths.Add(p => p.Customer.WithoutUpdate());

					//paths = pathBuilder.ToArray();

				if (adapter.Address != null ){
					if(adapter.Address.EntityKey == null) adapter.Address.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", adapter.Address);
				}
				if (adapter.Address1 != null ){
					if(adapter.Address1.EntityKey == null) adapter.Address1.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", adapter.Address1);
				}
				if (adapter.Customer != null ){
					if(adapter.Customer.EntityKey == null) adapter.Customer.EntityKey = con.WrappedContext.CreateEntityKey("Customers", adapter.Customer);
				}
#region Childs SalesOrderDetails 
				if (adapter.SalesOrderDetails != null)
                {
                    foreach (var item in adapter.SalesOrderDetails)
                    {
						
							if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderDetails", item);
							if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)){ 
								//paths.Add(p => p.SalesOrderDetails.First().WithoutUpdate());
								
						if (item.Product != null){
							item.Product.EntityKey = con.WrappedContext.CreateEntityKey("Products", item.Product);
                            
             
						}								
							if (item.SalesOrderHeader == null)
								item.SalesOrderHeader = adapter;

								item.EntityKey = null;
							}

                    }
					if (adapter.SalesOrderDetails.Count > 0){
						paths.Add(p => p.SalesOrderDetails.First().WithoutUpdate());
						paths.Add(p => p.SalesOrderDetails.First().Product.WithoutUpdate());
					
					}
                }
#endregion 




                //con.WrappedContext.AttachObjectGraph<SalesOrderHeaderAdapter>(adapter, p=>p.Address, p=>p.Address1, p=>p.Customer, p=>p.SalesOrderDetails);
                con.WrappedContext.AttachObjectGraph<SalesOrderHeaderAdapter>(adapter, paths.ToArray());
              	if (saveChanges){
                    con.WrappedContext.SaveChanges(SaveOptions.AcceptAllChangesAfterSave);
					 
				}
                else
                    con.WrappedContext.SaveChanges(SaveOptions.None);
                if (!saveChanges)
                    context = con.WrappedContext;
                else
                    context = null;
				itemResult = adapter.PocoEntity;
                OnCreated(this, e = new BusinessRulesEventArgs<SalesOrderHeader>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });
                return itemResult;
            }
        }
        BusinessRulesEventArgs<SalesOrderHeader> e = null;
        public void Create(List<SalesOrderHeader> entities)
        {
				ObjectContext context = null;
				foreach (SalesOrderHeader entity in entities)
				{
					this.Create(entity, true, out context);
				}

				
				
        }

        public SalesOrderHeader Update(SalesOrderHeader entity)
        {
			ObjectContext context = null;
            return Update(entity, true, out context, null);

        }
         public SalesOrderHeader Update(SalesOrderHeader entity, params Expression<Func<SalesOrderHeader, object>>[] paths)
        {
			  ObjectContext context = null;
            return Update(entity, true, out context, paths);
         }
        public SalesOrderHeader Update(SalesOrderHeader entity, bool saveChanges, out ObjectContext outcontext)
        {
			return Update(entity, saveChanges, out outcontext, null);
		}
         public SalesOrderHeader Update(SalesOrderHeader entity, bool saveChanges, out ObjectContext outcontext, params Expression<Func<SalesOrderHeader,object>>[] pocopaths)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
				SalesOrderHeader  itemResult = null;

	

				e = null;
                OnUpdating(this,e = new BusinessRulesEventArgs<SalesOrderHeader>() { Item=entity, PathExpressions = pocopaths, SaveChanges =saveChanges });
				   if (e != null) {
						if (e.Cancel)
						{
							outcontext = null;
							return e.Item;

						}
					}

                SalesOrderHeaderAdapter adapter = con.GetAdapterObject<SalesOrderHeaderAdapter>(entity);
                adapter.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderHeaders", adapter);
				    var es = con.SalesOrderHeaders;
				List<Expression<Func<SalesOrderHeaderAdapter, object>>> paths = new List<Expression<Func<SalesOrderHeaderAdapter,object>>>();
                if (pocopaths != null)
                {
					// Translate
                    foreach (var pocopath in pocopaths)
                    {
                        var param = Expression.Parameter(typeof(SalesOrderHeaderAdapter), "p");
                        var member = MemberExpression.PropertyOrField(param, ((System.Linq.Expressions.MemberExpression)(((System.Linq.Expressions.LambdaExpression)(pocopath)).Body)).Member.Name);
                        Expression<Func<SalesOrderHeaderAdapter, object>> path  = null;
                        switch(member.Member.Name){
                        
							case "SalesOrderDetails":
								//path = p => member;
								path = p => p.SalesOrderDetails.First().WithoutUpdate();
				//				path = p => p.SalesOrderDetails.First().Product.WithoutUpdate();											
							break;
							
							default:
								path = p => member;
							break;
                        }

                        paths.Add(path.Expand());
 					}
                }
                else {
                  paths = new List<Expression<Func<SalesOrderHeaderAdapter, object>>>();

					//List<Expression<Func<SalesOrderHeaderAdapter,object>>> pathBuilder = new List<Expression<Func<SalesOrderHeaderAdapter,object>>>();
					paths.Add(p => p.Address.WithoutUpdate());

					paths.Add(p => p.Address1.WithoutUpdate());

					paths.Add(p => p.Customer.WithoutUpdate());

		
					//paths = pathBuilder.ToArray();		
			}
			object aux = null;
				if (adapter.Address != null ){
					if(adapter.Address.EntityKey == null) adapter.Address.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", adapter.Address);
				}

                
				if (adapter.Address1 != null ){
					if(adapter.Address1.EntityKey == null) adapter.Address1.EntityKey = con.WrappedContext.CreateEntityKey("Addresses", adapter.Address1);
				}

                
				if (adapter.Customer != null ){
					if(adapter.Customer.EntityKey == null) adapter.Customer.EntityKey = con.WrappedContext.CreateEntityKey("Customers", adapter.Customer);
				}

                
				if (adapter.SalesOrderDetails != null)
                {
                    foreach (var item in adapter.SalesOrderDetails)
                    {

                        if (item.EntityKey == null) item.EntityKey = con.WrappedContext.CreateEntityKey("SalesOrderDetails", item);
						if (!con.WrappedContext.TryGetObjectByKey(item.EntityKey, out aux)) item.EntityKey = null;
                        
                    }
                }



                //con.AttachObjectGraph<SalesOrderHeader>(adapter, p=>p.Address, p=>p.Address1, p=>p.Customer, p=>p.SalesOrderDetails);
                con.WrappedContext.AttachObjectGraph<SalesOrderHeaderAdapter>(adapter, paths.ToArray());
				if (saveChanges){
                	con.WrappedContext.SaveChanges();
					 
					}
                if(!saveChanges)
					outcontext = con.WrappedContext;
				else
					outcontext = null;
				itemResult = adapter.PocoEntity;
				OnUpdated(this, e = new BusinessRulesEventArgs<SalesOrderHeader>() { Item=itemResult, PathExpressions = pocopaths, SaveChanges =saveChanges });

              	return itemResult;

			  }
        }
        public SalesOrderHeader Save(SalesOrderHeader entity)
        {
			return Save(entity, true, null);
        }
        public int Save(List<SalesOrderHeader> entities)
        {
			using (EFPocoContext con = new EFPocoContext())
			{
			
            int n = 0;
            foreach (SalesOrderHeader item in entities)
            {
                try
                {
                    this.Save(item, false, con);
                    n++;
                }catch (Exception ex){
                    SFSdotNet.Framework.My.EventLog.Exception(ex);
                }
            }
            con.SaveChanges();
            return n;
            }
        }
        #endregion
        #region Delete
        public void Delete(SalesOrderHeader entity)
        {
				ObjectContext context = null;
				this.Delete(entity, true, out context);
			
        }

        
        public void Delete(SalesOrderHeader entity, bool saveChanges, out  ObjectContext context)
        {
			using (EFPocoContext _con = new EFPocoContext())
			{
				int result = 0;
				
               	BusinessRulesEventArgs<SalesOrderHeader> _e = null;
                OnDeleting(this,_e = new BusinessRulesEventArgs<SalesOrderHeader>() { Item=entity, SaveChanges =saveChanges });
				   if (_e != null) {
						if (_e.Cancel)
						{
							context = null;
							return;

						}
					}


				SalesOrderHeaderAdapter adapter = _con.GetAdapterObject<SalesOrderHeaderAdapter>(entity);
                adapter.EntityKey = _con.WrappedContext.CreateEntityKey("SalesOrderHeaders", adapter);
                
	            //adapter = _con.WrappedContext.AttachObjectGraph<SalesOrderHeaderAdapter>(adapter);
				_con.WrappedContext.AttachTo("SalesOrderHeaders", adapter);
                
									_con.WrappedContext.DeleteObject(adapter);
                				
				if (!saveChanges)
                    context = _con.WrappedContext;
                else
                    context = null;
				 SaveOptions saveOption = SaveOptions.None;
                if (saveChanges)
                    saveOption = SaveOptions.AcceptAllChangesAfterSave;

				result = _con.WrappedContext.SaveChanges(saveOption);
				if (saveChanges){
					
					}
				if (_e == null)
					_e = new BusinessRulesEventArgs<SalesOrderHeader>() { Item = entity };
                OnDeleted(this, _e );

				//return null;
			}            
        }
        public void Delete(List<SalesOrderHeader> entities)
        {
				ObjectContext context = null;
			
				foreach (SalesOrderHeader item in entities)
				{
					this.Delete(item, true, out context);
				}
			

			
        }
        #endregion
 
        #region GetCount
        public int GetCount(Expression<Func<SalesOrderHeader, bool>> predicate)
        {
		
			using (EFPocoContext con = new EFPocoContext())
			{


				if (predicate == null) predicate = PredicateBuilder.True<SalesOrderHeader>();
				
				return con.SalesOrderHeaders.Count(predicate);
			}

        }
        public int GetCount(string predicate)
        {
			e = null;
            OnCounting(this, e = new BusinessRulesEventArgs<SalesOrderHeader>() {  FilterExpressionString = predicate });
            if (e != null)
            {
                if (e.Cancel)
                {
                    context = null;
                    return e.CountResult;

                }
                predicate = e.FilterExpressionString;
            
            }
					predicate = GetSpecificFilter(predicate);
			using (EFContext con = new EFContext())
			{
				   
                string predicateWithManyRelations = "";
                string predicateWithFKAndComputed = "";
                QueryUtils.BreakeQuery1(predicate, ref predicateWithManyRelations, ref predicateWithFKAndComputed);

                if (!string.IsNullOrEmpty(predicate))
                {
				
					
                    return con.SalesOrderHeaders.Count(System.Linq.Dynamic.DynamicExpression.ParseLambda<SalesOrderHeader, bool>(predicate));
					
                }else
                    return con.SalesOrderHeaders.Count();

			}

		}
         public int GetCount()
        {
            return GetCount(p => true);
        }
        #endregion
        
         public SalesOrderHeader Update(SalesOrderHeader entity, string paths)
        {
            return Update(entity, paths.Split(char.Parse(",")));
            
        }

        public SalesOrderHeader Update(SalesOrderHeader entity, string[] paths)
        {
            // Translate
            List<Expression<Func<SalesOrderHeader, object>>> pathList = new List<Expression<Func<SalesOrderHeader, object>>>();
            for (int i = 0; i <= paths.Length -1; i++)
            {
                var param = Expression.Parameter(typeof(SalesOrderHeader), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<SalesOrderHeader, object>> path = p => member;
                pathList.Add(path.Expand());
            }
           return Update(entity, pathList.ToArray());
        }

        public void Update(List<SalesOrderHeader> entities, string paths)
        {
            foreach (var entity in entities )
            {
                Update(entity, paths);
            }
        }

        public SalesOrderHeader Create(SalesOrderHeader entity, string paths)
        {
			if(string.IsNullOrEmpty(paths))
				return Create(entity);
				
            return Create(entity, paths.Split(char.Parse(",")));
        }

        public  void Create(List<SalesOrderHeader> entities, string paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }

        public void Create(List<SalesOrderHeader> entities, string[] paths)
        {
            foreach (var entity in entities)
            {
                Create(entity, paths);
            }
        }
        
        public SalesOrderHeader  Create(SalesOrderHeader entity, string[] paths)
        {
            List<Expression<Func<SalesOrderHeader, object>>> pathList = new List<Expression<Func<SalesOrderHeader, object>>>();
            for (int i = 0; i < paths.Length - 1; i++)
            {
                var param = Expression.Parameter(typeof(SalesOrderHeader), "p");
                var member = MemberExpression.PropertyOrField(param, paths[i]);

                Expression<Func<SalesOrderHeader, object>> path = p => member;
                pathList.Add(path.Expand());
            }
            return Create(entity, pathList.ToArray());
        }
        public void Delete(List<SalesOrderHeader.CompositeKey> entityKeys)
        {

            List<SalesOrderHeader> items = new List<SalesOrderHeader>();
            foreach (var itemKey in entityKeys)
            {
                items.Add(GetByKey(itemKey.SalesOrderID));
            }

            Delete(items);

        }
		
		
	}
	 
}


